<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use App\Libs\wrapper\Login;
use App\Models\Common\Constant;
use App\Models\ResourceModel\SelfSpuColor;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Models\ResourceModel\CustomSkuModel;
use App\Models\ResourceModel\SkuModel;
use App\Models\ResourceModel\SpuModel;

class SelfSpu extends BaseModel
{
    protected $selfSpuColorModel;

    public function __construct()
    {
        $this->selfSpuColorModel = new SelfSpuColor();
    }



    public function SendAndBindSkuI($params){
    
        $p['row'] = ['old_sku','custom_sku','user','shop_name'];
        $p['file'] = $params['file'];
        $p['start'] = 2;
        $data =  $this->CommonExcelImport($p);
        db::beginTransaction(); 
        $rt = [];
        foreach ($data as $v) {
            # code...
            if(!empty($v['custom_sku'])){
                try {
                    //code...
                   $r =  $this->SendAndBindSku($v);
                } catch (\Throwable $th) {
                    //throw $th;
                    db::rollback();// 回调
                    return ['type'=>'fail','msg'=>$th->getMessage()];
                }

                if($r['type']=='fail'){
                    db::rollback();// 回调
                    return ['type'=>'fail','msg'=>$r['msg']];
                }

                $rt[] = $r['data'];
            }
        }
        db::commit();
        
        return ['msg'=>'导入成功','type'=>'success','data'=>$rt];
        
    
    }
    public function SendAndBindSku($params){


        $shop_name = $params['shop_name'];
        $user = $params['user'];
        $custom_sku = $params['custom_sku'];
        $old_sku = $params['old_sku'];

        $users = db::table('users')->where('account',$user)->first();
        if(!$users){
            return ['type'=>'fail','msg'=>'无此用户'.$user];
        }

        $user_id = $users->Id;

        $shops = db::table('shop')->where('shop_name',$shop_name)->first();
        if(!$shops){
            return ['type'=>'fail','msg'=>'无此店铺'.$shop_name];
        }

        $shop_id = $shops->Id;


        $cusres = db::table('self_custom_sku')->where('custom_sku',$custom_sku)->orwhere('old_custom_sku',$custom_sku)->first();
        if(!$cusres){
            return ['type'=>'fail','msg'=>'无此customsku'.$custom_sku];
        }

        $a_shop_id = str_pad($shop_id, 3, 0, STR_PAD_LEFT);
        $shop_identifying = $shops->identifying;
        if(empty($shop_identifying)){
            return ['type'=>'fail','msg'=>'该店铺没有标识，请添加后再尝试生成'];
        }
        $sku = $shop_identifying.$a_shop_id.'-'.$custom_sku.'-1';
        
        
        $sku_i['sku'] = $sku;
        $sku_i['shop_id'] = $shop_id;
        $sku_i['custom_sku'] = $custom_sku;
        $sku_i['spu'] = $cusres->spu;
        $sku_i['user_id'] = $user_id;
        $sku_i['create_time'] = time();
        $sku_i['operate_user_id'] = $user_id;
        $sku_i['old_sku'] =  $old_sku;
        $sku_i['spu_id'] = $cusres->spu_id;
        $sku_i['custom_sku_id'] = $cusres->id;

        $is_repeat = db::table('self_sku')->where('sku',$sku)->first();
        

        if($is_repeat){
            return ['type'=>'fail','msg'=>'该sku已生成'.$sku.'---'.$custom_sku.'--'.$is_repeat->sku];
        }

        db::table('self_sku')->insert($sku_i);

        return ['type'=>'success','data'=>$old_sku.'->'.$sku];
    }




    public function expord_old_spu($params){
            ////获取Excel文件数据
            $file = $params['file'];
            //spu custom_sku sku color_id size_id  platform_id one_cate three_cate shop_id name
              //获取文件后缀名
            $extension = $file->getClientOriginalExtension();
            if ($extension == 'csv') {
                $PHPExcel = new \PHPExcel_Reader_CSV();
            } elseif ($extension == 'xlsx') {
                $PHPExcel = new \PHPExcel_Reader_Excel2007();
            } else {
                $PHPExcel = new \PHPExcel_Reader_Excel5();
            }

            if (!$PHPExcel->canRead($file)) {
                return [
                    'type' => 'fail',
                    'msg' => '导入失败，Excel文件错误'
                ];
            }

            $PHPExcelLoad = $PHPExcel->load($file);
            $Sheet = $PHPExcelLoad->getSheet(0);
            $add_list = array();
            /**取得一共有多少行*/
            $allRow = $Sheet->getHighestRow();
            $ai = 0;
            for ($j = 2; $j <= $allRow; $j++) {
                
                $add_list[$j - 2]['shop_id'] = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
                if(!empty($add_list[$j - 2]['shop_id'])){
                    $ai++;
                    $add_list[$j - 2]['spu'] = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
                    $add_list[$j - 2]['sku'] = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
                    $add_list[$j - 2]['one_cate'] = trim($Sheet->getCellByColumnAndRow(3, $j)->getValue());
                    if(!$add_list[$j - 2]['one_cate']){
                        return [
                                'type' => 'fail',
                                'msg' => '导入失败,一类必填，行-'.$j.'列-'.'4'
                            ];
                    }
                    $add_list[$j - 2]['three_cate'] = trim($Sheet->getCellByColumnAndRow(4, $j)->getValue());
                    $color_name =  trim($Sheet->getCellByColumnAndRow(5, $j)->getValue());
                    $identifying = trim($Sheet->getCellByColumnAndRow(6, $j)->getValue());
                    $color_res = Db::table('self_color_size')->where('identifying',$identifying)->first();
                    if(!$color_res){
                        // return [
                        //     'type' => 'fail',
                        //     'msg' => '导入失败，无该颜色标识'.$identifying
                        // ];
                        $colorres['identifying'] = $identifying;
                        $colorres['name'] = $color_name;
                        $colorres['type'] = 1;
                        $id = $this->ColorSizeAdd($colorres);
                        if(!isset($id['id'])){
                            return $id;
                        }
                        $color_id = $id['id'];    
                    }else{
                        $color_id = $color_res->id;
                    }
                   
                    $add_list[$j - 2]['color_id'] = $color_id;
                    
                    $size = trim($Sheet->getCellByColumnAndRow(7,$j)->getValue());
                    $size_res = Db::table('self_color_size')->where('identifying',$size)->first();
                    if(!$size_res){
                        return [
                            'type' => 'fail',
                            'msg' => '导入失败，无该尺码'.$size
                        ];
                    }
                    $size_id = $size_res->id;
                    $add_list[$j - 2]['size_id'] = $size_id;
                    $add_list[$j - 2]['custom_sku'] = trim($Sheet->getCellByColumnAndRow(8, $j)->getValue());
                    $add_list[$j - 2]['name'] = trim($Sheet->getCellByColumnAndRow(9, $j)->getValue());
                    $add_list[$j - 2]['market'] = trim($Sheet->getCellByColumnAndRow(10, $j)->getValue());
                    $add_list[$j - 2]['platform_id'] = 5;
                }
              
            }

            // return ['type'=>'fail','msg'=>$add_list];
            $bi = 0;
           foreach ($add_list as $key => $value) {
            # code...
                if(!empty($value['spu'])){
                    $res = $this->oldspu($value);
                    if($res==1){
                        $bi++;
                    }else{
                        return $res;
                    }
                }
              
           }

        //    echo '导入成功,数据'.$ai.'录入'.$bi;
           return ['type'=>'success','msg'=>'导入成功,数据'.$ai.'录入'.$bi];
    }



    //批量绑定新旧sku
    public function expord_bind_sku($params){
        ////获取Excel文件数据
        $file = $params['file'];
        $type = $params['type']??1;  
        //类型  1库存  2渠道
        //spu custom_sku sku color_id size_id  platform_id one_cate three_cate shop_id name
          //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }

        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);
        $i = 0;
        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();


        for ($j = 2; $j <= $allRow; $j++) {
            //新sku
            $new_sku = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            if($new_sku){

                //旧sku
                $old_sku = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
                // if(!$old_sku){
                //     return [
                //         'type' => 'fail',
                //         'msg' => '导入失败，无对应旧sku'.$new_sku
                //     ];
                // }

                if($type==1){
                    $name = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
                    if($name){
                        $update['name'] = $name;
                    }
                    if (!empty($old_sku)){
                        $update['old_custom_sku'] = $old_sku;
                    }

                    $skus = DB::table('self_custom_sku')->where('custom_sku',$new_sku)->first();
                    if(!$skus){
                        return [
                            'type' => 'fail',
                            'msg' => '导入失败，此sku未生成'.$new_sku
                        ];
                    }
                    // 判断是否重复绑定
                    if (!empty($old_sku)){
                        $check = DB::table('self_custom_sku')->where('old_custom_sku',$old_sku)->where('id','!=',$skus->id)->first();
                        if (!empty($check)){
                            return [
                                'type' => 'fail',
                                'msg' => '导入失败，此sku已存在！不可重复绑定'.$new_sku
                            ];
                        }
                    }
                    if(!empty($update)){
                        DB::table('self_custom_sku')->where('custom_sku',$new_sku)->update($update);
                    }

                    $i++;

                }else{
                    $name = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
                    if (!empty($old_sku)){
                        $update['old_sku'] = $old_sku;
                    }
                    $skus = DB::table('self_sku')->where('sku',$new_sku)->first();
                    if(!$skus){
                        return [
                            'type' => 'fail',
                            'msg' => '导入失败，此sku未生成'.$new_sku
                        ];
                    }
                    $custom_sku_id = $skus->custom_sku_id;
                    if($name){
                        $cus_update['name'] = $name;
                        DB::table('self_custom_sku')->where('id',$custom_sku_id)->update($cus_update);
                    } 
                    // 判断是否重复绑定
                    if (!empty($old_sku)){
                        $check = DB::table('self_sku')->where('old_sku',$old_sku)->where('id','!=',$skus->id)->first();
                        $check_s = DB::table('self_spu')->where('old_spu',$old_sku)->orwhere('spu',$old_sku)->first();
                        if($check_s){
                            return [
                                'type' => 'fail',
                                'msg' => '导入失败，此sku与spu相同存在！不可重复绑定'.$new_sku
                            ];
                        }
                        if (!empty($check)){
                            return [
                                'type' => 'fail',
                                'msg' => '导入失败，此sku已存在！不可重复绑定'.$new_sku
                            ];
                        }
                    }
                    if(!empty($update)){
                        DB::table('self_sku')->where('sku',$new_sku)->update($update);
                    }
                    $i++;
                }

            }

        }
         
       return ['type'=>'success','msg'=>'导入成功,导入数据'.$i.'条'];
    }

    //shop_id spu sku 大类  小类 颜色标识 尺码  custom_sku product_name 
    public function oldspu($params){


        // {"shop_id":"344","spu":"CFMWY00055","sku":"SE-CFMWY00055-1BlackRedM","one_cate":"UM","three_cate":"FH","color_id":40,"size_id":46,"custom_sku":"CFMWY00055-1BlackRedM","name":"男士印花加绒卫衣055-1 黑红 M码","market":"U","platform_id":5}
        $spu = $params['spu'];
        $spures = Db::table('self_spu')->where('old_spu',$spu)->first();
        if(!$spures){
            //如果没有spu  则需要重新生成绑定

            //生成
            $one_cate_res = Db::table('self_category')->where('identifying',$params['one_cate'])->first();

            $three_res = Db::table('self_category')->where('identifying',$params['three_cate'])->get();
            if(!$one_cate_res){
                return ['type'=>'fail','msg'=>'缺少大类'.$params['one_cate']];
            }
            if(!$three_res){
                return ['type'=>'fail','msg'=>'缺少三类'.$params['one_cate'].'-'.$params['three_cate']];
            }

            foreach ($three_res as $key => $value) {
                # code...
                $two_res = Db::table('self_category')->where('id',$value->Id)->where('fid',$one_cate_res->Id)->first();
                if(!$two_res){
                    return ['type'=>'fail','msg'=>'大类三类中缺少二类'.$params['one_cate'].'-'.$params['three_cate']];
                }else{
                    $three_cate_res = $value;
                }
                
            }



            $spuinsert['one_cate_id']  = $one_cate_res->Id;
            $spuinsert['two_cate_id']  = $two_res->Id;
            $spuinsert['three_cate_id'] = $three_cate_res->Id;
            $spuinsert['type'] = 1;
            $spuinsert['platform_id'] = $params['platform_id'];
            $spuinsert['user_id'] = 1;
            $spuinsert['posttype'] = 2;

            // echo '生成';
            // var_dump($spuinsert);
            $newspu = $this->SpuPreviewb($spuinsert);
            if( $newspu['type']!='success'){
                return ['type'=>'fail','msg'=>$newspu['msg'].$spu];
            }
            $newspu = $newspu['spu'];

            //绑定
            Db::table('self_spu')->where('spu',$newspu)->update(['old_spu'=>$spu]);
            $spu_id = Db::table('self_spu')->where('old_spu',$spu)->first();
            $spu_id = $spu_id->id;
        }else{
            $spu_id = $spures->id;
        }


        $custom_sku = $params['custom_sku'];
        $custom_skures = Db::table('self_custom_sku')->where('old_custom_sku',$custom_sku)->first();
        if(!$custom_skures){
            //如果没有库存sku   则需要重新生成绑定

            //生成
            $cusinsert['spu_id'] = $spu_id;
            $cusinsert['color_id'] = $params['color_id'];
            $cusinsert['size_id'] = $params['size_id'];
            $cusinsert['user_id'] = 1;
            $cusinsert['market'] =  $params['market'];
            $newcus = $this->SkuPreview($cusinsert);
            if( $newcus['type']!='success'){
                return ['type'=>'fail','msg'=>$newcus['msg'].$custom_sku];
            }

            $newcustom_sku_res = $newcus['data']['data'];
            $newcustom_sku = $newcustom_sku_res[0]['custom_sku'];

            $is_repeat = Db::table('self_custom_sku')->where('custom_sku',$newcustom_sku)->first();
            echo ''."\n";

            $cuscreate['user_id'] = 1;
            $cuscreate['operate_user_id'] = 1;
            $cuscreate['custom_sku'][0] = $newcustom_sku;
            // return ['type'=>'fail','msg'=>$cuscreate];
            if(!$is_repeat){
                $res = $this->CustomSkuCreate($cuscreate);
                if( $res['type']!='success'){
                    return $res;
                }
            }

            //绑定
            Db::table('self_custom_sku')->where('custom_sku',$newcustom_sku)->update(['old_custom_sku'=>$custom_sku,'name'=>$params['name']]);

        }

        $sku = $params['sku'];
        $skures = Db::table('self_sku')->where('old_sku',$sku)->first();
        if(!$skures){
            //如果没有库存sku   则需要重新生成绑定
            //生成
            $skuinsert['spu_id'] = $spu_id;
            $skuinsert['color_id'] = $params['color_id'];
            $skuinsert['size_id'] = $params['size_id'];
            $skuinsert['user_id'] = 1;
            $shopids[0] = $params['shop_id'];
            $skuinsert['shop_id'] = $shopids;
            $newsku = $this->SkuPreview($skuinsert);
            // var_dump($newsku);
            if( $newsku['type']!='success'){
                return ['type'=>'fail','msg'=>$newsku['msg'].$sku];
            }
            $newsku_res = $newsku['data']['data'];
            $new_sku = $newsku_res[0]['sku'];
            $skucreate['user_id'] = 1;
            $skucreate['operate_user_id'] = 1;
            $skucreate['sku'][0] = $new_sku;
            $isreport = $this->GetSku($new_sku);
            if($isreport){
                return ['type'=>'fail','msg'=>$sku.'该新sku已被绑定'.$new_sku];
            }

            $skucreate['shop_id'] = $params['shop_id'];
            $cs = $this->SkuCreateb($skucreate);
            if( $cs['type']!='success'){
                return $cs;
            }
            //绑定
            Db::table('self_sku')->where('sku',$new_sku)->update(['old_sku'=>$sku]);

        }
        // else{
        //     return ['type'=>'fail','msg'=>'导入重复数据'.$sku];
        // }

        return 1;
    }

    //品类excel导入
    public function CateImport($params)
    {

        ////获取Excel文件数据
        $user_id = $params['user_id'];

        $file = $params['file'];

        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }

        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);
        $add_list = array();
        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        for ($j = 2; $j <= $allRow; $j++) {
            $add_list[$j - 2]['name_1'] = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            $add_list[$j - 2]['identifying_1'] = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
            $add_list[$j - 2]['name_2'] = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
            $add_list[$j - 2]['identifying_2'] = trim($Sheet->getCellByColumnAndRow(3, $j)->getValue());
            $add_list[$j - 2]['name_3'] = trim($Sheet->getCellByColumnAndRow(4, $j)->getValue());
            $add_list[$j - 2]['identifying_3'] = trim($Sheet->getCellByColumnAndRow(5, $j)->getValue());
          
        }

          $time = time();
          // 处理数据
          $list = array();
          foreach ($add_list as $k => $v) {
              // 大类
              $name_1 = array_column($list, 'name');// 提取数组某个键值
              $key_1 = array_search($v['name_1'], $name_1);// 字符串在数组的键值
              if ($key_1 === false) {
                  // 不存在
                  $list[] = array(
                      'name' => $v['name_1'],
                      'identifying' => $v['identifying_1'],
                      'children' => array()
                  );
  
                  $name_1 = array_column($list, 'name');
                  $key_1 = array_search($v['name_1'], $name_1);
              }
  
              // 二类
              $name_2 = array_column($list[$key_1]['children'], 'name');
              $key_2 = array_search($v['name_2'], $name_2);
              if ($key_2 === false) {
                  // 不存在
                  $list[$key_1]['children'][] = array(
                      'name' => $v['name_2'],
                      'identifying' => $v['identifying_2'],
                      'children' => array()
                  );
  
                  $name_2 = array_column($list[$key_1]['children'], 'name');// 提取数组某个键值
                  $key_2 = array_search($v['name_2'], $name_2);// 字符串在数组的键值
              }
  
              // 三类
              $name_3 = array_column($list[$key_1]['children'][$key_2]['children'], 'name');// 提取数组某个键值
              $key_3 = array_search($v['name_3'], $name_3);// 字符串在数组的键值
              if ($key_3 === false) {
                  // 不存在
                  $list[$key_1]['children'][$key_2]['children'][] = array(
                      'name' => $v['name_3'],
                      'identifying' => $v['identifying_3'],
                      'children' => array()
                  );
              }
          }
  
          //// 存储数据
          if (empty($list)) {
            return ['type'=>'fail','msg'=>'数据为空导入失败'];
          }
  
          //添加数据
          foreach ($list as $k => $v) {
              //// 新增大类
              // 大类是否存在
              $sql = "select `id`
                          from self_category
                          where fid=0 and `type`=1 and (`name`='{$v['name']}' or `identifying`='{$v['identifying']}')
                          limit 1";
              $find_1 = json_decode(json_encode(db::select($sql)), true);
              if (empty($find_1)) {
                  // 新增大类
                  $arr = array();
                  $arr['fid'] = 0;
                  $arr['name'] = $v['name'];
                  $arr['identifying'] = $v['identifying'];
                  $arr['user_id'] = $user_id;
                  $arr['create_time'] = $time;
                  $arr['status'] = 1;
                  $arr['type'] = 1;
                  $add_1 = db::table('self_category')->insertGetid($arr);
                  if ($add_1) {
                      $fid_1 = $add_1;
                  } else {
                      continue;
                  }
              } else {
                  $fid_1 = $find_1[0]['id'];
              }
  
              //// 新增二类
              foreach ($v['children'] as $k1 => $v1) {
                  // 二类是否存在
                  $sql = "select `id`
                              from self_category
                              where fid={$fid_1} and `type`=2 and (`name`='{$v1['name']}' or `identifying`='{$v1['identifying']}')
                              limit 1";
                  $find_2 = json_decode(json_encode(db::select($sql)), true);
                  if (empty($find_2)) {
                      // 新增二类
                      $arr = array();
                      $arr['fid'] = $fid_1;
                      $arr['name'] = $v1['name'];
                      $arr['identifying'] = $v1['identifying'];
                      $arr['user_id'] = $user_id;
                      $arr['create_time'] = $time;
                      $arr['status'] = 1;
                      $arr['type'] = 2;
                      $add_2 = db::table('self_category')->insertGetid($arr);
                      if ($add_2) {
                          $fid_2 = $add_2;
                      } else {
                          continue;
                      }
                  } else {
                      $fid_2 = $find_2[0]['id'];
                  }
  
                  //// 新增三类
                  foreach ($v1['children'] as $k2 => $v2) {
                      // 三类是否存在
                      $sql = "select `id`
                                  from self_category
                                  where fid={$fid_2} and `type`=3 and (`name`='{$v2['name']}' or `identifying`='{$v2['identifying']}')
                                  limit 1";
                      $find_3 = json_decode(json_encode(db::select($sql)), true);
                      if (empty($find_3)) {
                          // 新增三类
                          $arr = array();
                          $arr['fid'] = $fid_2;
                          $arr['name'] = $v2['name'];
                          $arr['identifying'] = $v2['identifying'];
                          $arr['user_id'] = $user_id;
                          $arr['create_time'] = $time;
                          $arr['status'] = 1;
                          $arr['type'] = 3;
                          $add_3 = db::table('self_category')->insertGetid($arr);
                          if (!$add_3) {
                              continue;
                          }
                      }
                  }
              }
          }
  
          return ['type'=>'success','msg'=>'导入成功'];
    }

    //一次性获取所有分类
    public function CateListAll(){
        $one_cates = Db::table('self_category')->where('status',1)->where('fid',0)->get();
        foreach ($one_cates as $v) {
            # code...

            $two_cate = Db::table('self_category')->where('status',1)->where('fid', $v->Id)->get();
            foreach ($two_cate as $tv) {
                # code...

                $three_cate = Db::table('self_category')->where('status',1)->where('fid', $tv->Id)->get();
   
                $tv->cates = $three_cate;
            }

            $v->cates = $two_cate;
        }
        return ['data'=>$one_cates,'type'=>'success'];
    }
   
    //分类列表
    public function CateList($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $where['status'] = 1;
        if(isset($params['fid'])){
            $where['fid'] = $params['fid'];
        }
        if(isset($params['name'])){
            $where['name'] = $params['name'];
        }
        if(isset($params['identifying'])){
            $where['identifying'] = $params['identifying'];
        }
        if(isset($params['type'])){
            $where['type'] = $params['type'];
        }

        $list = Db::table('self_category')->where($where);
        $totalNum = $list->count(); 
        $list = $list->offset($page)->limit($limit)->get(['id','name','fid','type','identifying','supervisor_id']);


        foreach ($list as $v) {
            $v->supervisor_name = '';
            if($v->supervisor_id!=''){
                $fz_id = explode(',',$v->supervisor_id);
                foreach ($fz_id as $u){
                    $account = $this->GetUsers($u);
                    $v->supervisor_name .= $account['account'].',';
                }
                $v->supervisor_name = rtrim( $v->supervisor_name,',');
            }
            $v->hasChildren = true;
            if($v->type==3){
                $v->hasChildren = false;
            }
        }
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];
    }

    public function ProductUserInfoList($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $type = $params['type']??1;

        $list = db::table('product_user_info')->where('type',$type);

        if(isset($params['status'])){
            $list = $list->where('status',$params['status']);
        }

        if(isset($params['company_name'])){
            $list = $list->where('company_name','like','%'.$params['company_name'].'%');
        }

        
        if(isset($params['user_name'])){
            $list = $list->where('user_name','like','%'.$params['user_name'].'%');
        }

        $totalNum = $list->count();
        $list = $list->offset($page)->limit($limit)->get();


        $posttype = $params['posttype']??1;
        if($posttype==2){
            if($type==1){
                $title_name = '货代管理';
            }else{
                $title_name = '发货地址管理';
            }
            
            $p['title']=$title_name.time();
            $p['title_list']  = [
                'company_name'=>'公司名',
                'user_name'=>'用户名',
                'addr'=>'地址',
                'phone'=>'电话',
                'desc'=>'备注',
            ];

            // $this->excel_expord($p);
                
            $p['data'] =   $list;
            $p['user_id'] =$params['find_user_id']??1;
            $p['type'] = $title_name.'-导出';
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type'=>'fail','msg'=>'加入队列失败'];
            }
            return ['type'=>'success','msg'=>'加入队列成功'];
        }

        
        return [
            'type' => 'success',
            'data' =>  $list,
            'totalNum' => $totalNum,
            'msg'=>'请求成功'
        ];

    }


    public function ProductUserInfoAdd($params){


        $i['type'] = $params['type']??1;
        if(isset($params['company_name'])){
            $i['company_name'] = $params['company_name'];
        }
        if(isset($params['user_name'])){
            $i['user_name'] = $params['user_name'];
        }
        if(isset($params['phone'])){
            $i['phone'] = $params['phone'];
        }
        if(isset($params['addr'])){
            $i['addr'] = $params['addr'];
        }
        if(isset($params['desc'])){
            $i['desc'] = $params['desc'];
        }
        $i['create_user'] = $params['user_id'];
        $i['create_time'] = date('Y-m-d H:i:s',time());

        $i['status'] = $params['status']??1;

        db::table('product_user_info')->insert($i);

        return ['type'=>'success','msg'=>'添加成功'];
    }


    public function ProductUserInfoUpdate($params){

        if(isset($params['id'])){
            $id = $params['id'];
        }else{
            return ['type'=>'fail','msg'=>'无必须参数id'];
        }

        if(isset($params['company_name'])){
            $i['company_name'] = $params['company_name'];
        }
        if(isset($params['user_name'])){
            $i['user_name'] = $params['user_name'];
        }
        if(isset($params['phone'])){
            $i['phone'] = $params['phone'];
        }
        if(isset($params['addr'])){
            $i['addr'] = $params['addr'];
        }
        if(isset($params['desc'])){
            $i['desc'] = $params['desc'];
        }

    
        $i['status'] = $params['status'];
        


        if(empty($i)){
            return['type'=>'fail','msg'=>'无修改项'];
        }
        db::table('product_user_info')->where('id',$id)->update($i);

        return ['type'=>'success','msg'=>'添加成功'];
    }


    public function ProductUserInfoDel($params){

        if(isset($params['id'])){
            $id = $params['id'];
        }else{
            return ['type'=>'fail','msg'=>'无必须参数id'];
        }

        db::table('product_user_info')->where('id',$id)->delete();

        return ['type'=>'success','msg'=>'删除成功'];
    }





    public function CateAdd($params){
        $add['type'] = $params['type'];
        $add['fid'] = $params['fid']??0;
        $add['name'] = $params['name'];
        $add['identifying'] = $params['identifying'];
        $isset = Db::table('self_category')
            ->where('fid',$add['fid'])
            ->where(function($query) use($add){
                $query->where('name',$add['name'])
                    ->orwhere(function($query)use($add){
                        $query->where('identifying',$add['identifying']);
                    });
            })
            ->first();
        if($isset){
            return ['type'=>'fail','msg'=>'同一类目下，类目名或标识重复'];
        }
        if ($params['fid'] == 0){
            // if (!isset($params['is_clothing'])){
            //     return ['type'=>'fail','msg'=>'未选择是否为服装类目'];
            // }
        }else{
            $cate = Db::table('self_category')
                ->where('Id',$params['fid'])
                ->first();
            if (empty($cate)){
                return ['type'=>'fail','msg'=>'上级类目不存在！'];
            }
            $params['is_clothing'] = $cate->is_clothing;
        }
        $add['is_clothing'] = $params['is_clothing']??0;
        $add['user_id'] = $params['user_id']??'';
        $add['create_time'] = time();
        $add['status'] = 1;

        $addresult = Db::table('self_category')->insert($add);
        
        if($addresult){
            return ['type'=>'success','msg'=>'添加成功'];
        }

    }


    public function CateUpdate($params){

        $add['type'] = $params['type'];
        $id = $params['id'];
        $add['fid'] = $params['fid']??0;
        $add['name'] = $params['name'];
        $add['identifying'] = $params['identifying'];
        $isset = Db::table('self_category')
            ->where('fid',$add['fid'])
            ->where('id','!=',$id)
            ->where(function($query) use($add){
                $query->where('name',$add['name'])
                    ->orwhere(function($query)use($add){
                        $query->where('identifying',$add['identifying']);
                    });
            })
            ->first();
        if($isset){
            return ['type'=>'fail','msg'=>'同一类目下，类目名或标识重复'];
        }
        
        $add['user_id'] = $params['user_id']??'';
        $add['create_time'] = time();
        $add['status'] = 1;

        $updateresult = Db::table('self_category')->where('id',$id)->update($add);

        //修改缓存字典
        Redis::Hset('datacache:category',$id, json_encode($add));
    
        
        if($updateresult){
            return ['type'=>'success','msg'=>'修改成功'];
        }
    }

    public function CateDel($params){

        $id = $params['id'];
        // $del['user_id'] = $params['user_id']??'';
        // $del['status'] = 2;
        $res = Db::table('self_category')->where('id',$id)->first();
        
        $type = $res->type;

        if($type==3){
            //三级类目   删除三类
            Db::table('self_category')->where('id',$id)->delete();
            Redis::Hdel('datacache:category',$id);
        }elseif($type==2){
            //二级类目，
            //获取三类信息
            $threeres = Db::table('self_category')->where('fid',$id)->get();
            if($threeres){
                foreach ($threeres as $v) {
                    //删除三类
                    Db::table('self_category')->where('id',$v->Id)->delete();
                    //删除三类缓存
                    Redis::Hdel('datacache:category',$v->Id);
                }
            }
            //删除二类
            Db::table('self_category')->where('id',$id)->delete();
            //删除二类缓存
            Redis::Hdel('datacache:category',$id);
            
        }elseif($type==1){
            //一级类目
            //获取二类信息
            $twores = Db::table('self_category')->where('fid',$id)->get();
            if($twores){
                foreach ($twores as $v) {
                    # code...
                    //获取三类信息
                    $threeres =  Db::table('self_category')->where('fid',$v->Id)->get();
                    foreach ($threeres as $tv) {
                        //根据三类id删除三类
                        Db::table('self_category')->where('id',$tv->Id)->delete();
                        //删除三类缓存
                        Redis::Hdel('datacache:category',$tv->Id);
                    }
                    //根据二类id删除二类
                    Db::table('self_category')->where('id',$v->Id)->delete();
                    //删除二类缓存
                    Redis::Hdel('datacache:category',$v->Id);
                }
            }
            //删除一类
            Db::table('self_category')->where('id',$id)->delete();

        }


        
        return ['type'=>'success','msg'=>'删除成功'];
        
    }


    //分类列表
    public function ColorSizeList($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }




        $where['status'] = 1;


        if(isset($params['identifying'])){
            $where['identifying'] = $params['identifying'];
        }
        if(isset($params['english_name'])){
            $where['english_name'] = $params['english_name'];
        }


        if(isset($params['user_id'])){
            $where['user_id'] = $params['user_id'];
        }


        $where['type'] = 1;
        if(isset($params['type'])){
            $where['type'] = $params['type'];
        }

        if(isset($params['type'])){
            $where['type'] = $params['type'];
        }



        $list = Db::table('self_color_size')->where($where);

        $is_old = $params['is_old']??1;

        if($is_old==0){
            $list = $list->where('color_class','!=','C');
        }

        if(isset($params['color_class'])){
            $list = $list ->where('color_class',$params['color_class']);
        }

        if(isset($params['name'])){
            $list = $list ->where('name','like','%'.$params['name'].'%');
        }

        $totalNum = $list ->count();
        // DB::connection()->enableQueryLog();
        $list = $list->offset($page)->limit($limit)->orderby('id','DESC')->get(['id','img','name','type','identifying','english_name','sort','user_id','color_class','class_num', 'fabric_color']);

        // var_dump(DB::getQueryLog());
        foreach ($list as $v) {
            # code...
            $v->account = '';
            $v->account = $this->GetUsers($v->user_id)['account'];
            $v->color_class_name = '';
            $res = db::table('self_color_system')->where('identifying',$v->color_class)->first();
            if($res){
                $v->color_class_name = $res->name;
            }
        }
        
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];
    }


    //获取spu对应颜色
    public function GetSpuColorBySpu($params){

        $spu_id = $params['id'];

        $spures = Db::table('self_spu')->where('id',$spu_id)->first();

        $list = Db::table('self_spu_color as a')
        ->leftjoin('self_color_size as b','a.color_id','=','b.id')
        ->where('a.base_spu_id', $spures->base_spu_id)
        ->get(['a.id','b.id as color_id','b.name','b.identifying','b.english_name','a.img','a.user_id']);        
        foreach ($list as $key => $value) {
            # code...
            $value->spu = $spures->spu;
            $users = $this->GetUsers($value->user_id);
            $value->user_name = $users['account']??'';
        }
        return [
            'data' => $list
        ];
    }

    //获取基础spu对应颜色
    public function GetSpuColorByBaseSpu($params){

        $base_spu_id = $params['id'];

        $list = Db::table('self_spu_color as a')
            ->leftjoin('self_color_size as b','a.color_id','=','b.id')
            ->where('a.base_spu_id',$base_spu_id)
            ->get(['a.id','b.id as color_id','b.name','b.identifying','b.english_name','a.img','a.user_id', 'a.order_start_quantity', 'b.fabric_color', 'a.fabric_color as spu_fabric_color']);
        foreach ($list as $key => $value) {
            # code...
            $users = $this->GetUsers($value->user_id);
            $value->user_name = $users['account']??'';
            $value->spu = Db::table('self_spu')->where('id',$base_spu_id)->first()->spu??'';
            $value->order_start_quantity = $value->order_start_quantity ?? 0;
            if (!empty($value->spu_fabric_color)){
                $value->fabric_color = $value->spu_fabric_color;
            }
        }
        return [
            'data' => $list
        ];
    }


    public function ColorAdd($params){


        $add['name'] = $params['name']??'';
        $add['color_class'] = $params['color_class'];
        $class_num = Db::table('self_color_size')->where('color_class', $add['color_class'])->orderby('class_num','desc')->first();
        if($class_num){
            $num = $class_num->class_num+1;
        }else{
            $num = 1;
        }
        $add['img'] = $params['img']??'';
        $add['class_num'] = str_pad($num, 2, 0, STR_PAD_LEFT);

        $add['identifying'] =  $add['color_class'].$add['class_num'];

        if(isset( $params['english_name'])){
            $add['english_name'] = $params['english_name']??'';
        }
       
        $is_create = $params['is_create']??0;
        if($is_create==0){
            return ['type'=>'success','msg'=>'预览成功','data'=>$add['identifying']];
        }

        $isset = Db::table('self_color_size')->where('identifying',$add['identifying'])->first();

        if($isset){
            return ['type'=>'fail','msg'=>'标识重复请刷新重试'.$add['name'].$add['identifying']];
        }
        $add['type'] = 1;
        $sort = Db::table('self_color_size')->where('type',$add['type'])->max('sort');
        $add['sort'] = $sort+1;
        $add['user_id'] = $params['user_id']??'';
        $add['create_time'] = time();
        $add['update_time'] = time();
        $add['status'] = 1;
        $add['card_code'] = $params['card_code']??'';
        $add['pd_code'] = $params['pd_code']??'';

        $addresult = Db::table('self_color_size')->insertGetId($add);
        if($addresult){
            return ['type'=>'success','msg'=>'添加成功','data'=>$addresult];
        }

    }


    //分类列表
    public function ColorClassList($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }
        $list = Db::table('self_color_system');

        $is_old = $params['is_old']??1;

        if($is_old==0){
            $list = $list->where('identifying','!=','C');
        }



        if(isset($params['identifying'])){
            $list = $list->where('identifying',$params['identifying']);
        }
        if(isset($params['name'])){
            $list = $list ->where('name','like','%'.$params['name'].'%')->orWhere('name','like','%'.$params['name'].'%');
        }


        $totalNum = $list ->count();
        // DB::connection()->enableQueryLog();
        $list = $list->offset($page)->limit($limit)->orderby('id','DESC')->get();

        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];
    }



    public function ColorSizeAdd($params){


        $add['name'] = $params['name'];
        $add['identifying'] = $params['identifying'];
        if(empty($add['name'])||empty($add['identifying'])){
            return ['type'=>'fail','msg'=>'名称或标识不能为空'];
        }
        $isset = Db::table('self_color_size')->where('name',$add['name'])->orwhere('identifying',$add['identifying']);
        if(isset( $params['english_name'])){
            $english_name = $params['english_name'];
            $isset  =  $isset  ->orwhere('english_name',$english_name);
        }
       
        $isset  =  $isset  ->first();

 
        // ->where(function($query) use($add){
        //     $query->where('name',$add['name'])
        //         ->orwhere(function($query)use($add){
        //             $query->where('identifying',$add['identifying']);
        //         });
        // })
        if($isset){
            return ['type'=>'fail','msg'=>'名称或标识重复'.$add['name'].$add['identifying']];
        }
        $add['type'] = $params['type']??1;
        if($add['type']==1){
            $add['english_name'] = $params['english_name']??'';
        }
        $sort = Db::table('self_color_size')->where('type',$add['type'])->max('sort');
        $add['sort'] = $sort+1;
        $add['user_id'] = $params['user_id']??'';
        $add['create_time'] = time();
        $add['update_time'] = time();
        $add['status'] = 1;
        $add['card_code'] = $params['card_code']??'';
        $add['pd_code'] = $params['pd_code']??'';
        $add['fabric_color'] = $params['fabric_color'] ?? '';

        $addresult = Db::table('self_color_size')->insertGetId($add);
        if($addresult){
            return ['type'=>'success','msg'=>'添加成功','id'=>$addresult];
        }

    }


    public function ColorClassAdd($params){
        if(!isset($params['name'])||!isset($params['identifying'])){
            return ['type'=>'fail','msg'=>'缺少名称或标识'];
        }
        $add['name'] = $params['name'];
        $add['identifying'] = $params['identifying'];
        $addresult = Db::table('self_color_system')->insertGetId($add);
        if($addresult){
            return ['type'=>'success','msg'=>'添加成功'];
        }
    }


    public function ColorClassDel($params){
        if(!isset($params['ids'])){
            return ['type'=>'fail','msg'=>'需要id'];
        }
        $ids = $params['ids'];
        Db::table('self_color_system')->whereIn('id',$ids)->delete();
        return ['type'=>'success','msg'=>'删除成功'];
    }


    public function ColorSizeUpdate($params){

        $id = $params['id'];
        $add['sort'] = $params['sort'];
        $add['name'] = $params['name'];
        $add['english_name'] = $params['english_name'];
        $add['img'] = $params['img']??'';

        // $isset = Db::table('self_color_size')
        //     ->where('id','!=',$id)
        //     ->where(function($query) use($add){
        //         $query->where('english_name',$add['english_name']) ->orwhere('name',$add['name']);
        //     })
        //     ->first();

        // if($isset){
        //     return ['type'=>'fail','msg'=>'排序或名称重复'];
        // }
        $add['card_code'] = $params['card_code']??'';
        $add['pd_code'] = $params['pd_code']??'';
        $add['user_id'] = $params['user_id']??'';
        $add['type'] = $params['type']??1;
        // if($add['type']==1){
        //     $add['english_name'] = $params['english_name']??'';
        // }
        $add['update_time'] = time();
        $add['status'] = 1;
        $add['fabric_color'] = $params['fabric_color'] ?? '';

        $updateresult = Db::table('self_color_size')->where('id',$id)->update($add);

        //修改缓存字典
        Redis::Hset('datacache:colorsize',$id, json_encode($add));
        
        if($updateresult){
            return ['type'=>'success','msg'=>'修改成功'];
        }
    }

    public function ColorSizeDel($params){

        $id = $params['id'];
        // $del['user_id'] = $params['user_id']??'';
        // $del['status'] = 2;
        $delresult = Db::table('self_color_size')->where('id',$id)->delete();
        if($delresult){
            Redis::Hdel('datacache:colorsize',$id);
            return ['type'=>'success','msg'=>'删除成功'];
        }
    }
    

    //生成基础spu
    public function SpuPreviewByBase($params){
            
        $query['one_cate_id'] = $params['one_cate_id']??'';
        $query['two_cate_id'] = $params['two_cate_id']??'';
        $query['three_cate_id'] = $params['three_cate_id']??'';
        $query['content'] = $params['content']??'';
        $query['user_id'] = $params['user_id']??'';
        $query['is_new'] = $params['is_new']??0;
        $query['color_style'] = $params['color_style']??0;
        $query['seasonal_style'] = $params['seasonal_style']??0;
        $query['create_time'] = time();
        $query['fabric_composition'] = $params['fabric_composition'] ?? '';
        $query['class'] = $params['class'] ?? 1;
        $query['pici'] = $params['pici'] ?? 0;
        $query['cb_price'] = $params['cb_price'] ?? 0;

        $is_create = $params['is_create']??0;

        $one_cateres   =  Db::table('self_category')->where('id',$query['one_cate_id'])->first();
        $one_cate = $one_cateres->identifying;

        $three_cateres   =  Db::table('self_category')->where('id',$query['three_cate_id'])->first();
        $three_cate = $three_cateres->identifying;

        //正常spu
        $spures = Db::table('self_spu')->orderby('num','desc')->first();
        if(!$spures){
            $num = 1;
        }else{
            //查询编码
            $num = $spures->num+1;
        }

        //补足五位
        $query['num'] = str_pad($num, 5, 0, STR_PAD_LEFT);

        //正常spu 大类1位+三类2位+编号五位
        $baseSpu = $one_cate.$three_cate.$query['num'];
        if($is_create==1){
            $id = $params['id'] ?? 0;
            if (empty($id)){
                $query['spu'] = $baseSpu;
                $id = Db::table('self_spu')->insertGetId($query);
                if(!$id){
                    return ['type'=>'fail','msg'=>'生成失败'];
                }
            }else{
                $baseSpuMdl = Db::table('self_spu')->where('id', $id)->first();
                if (empty($baseSpuMdl)){
                    return ['type'=>'fail','msg'=>'更新失败,未查询到信息'];
                }
                $baseSpu = $baseSpuMdl->spu;
                $res = Db::table('self_spu')->where('id', $id)->update($query);
                if(!$res){
                    return ['type'=>'fail','msg'=>'更新失败'];
                }
            }
            $result['base_spu'] = $baseSpu;
            $result['base_spu_id'] = $id;
            return ['type'=>'success','msg'=>'生成成功','spu'=>$result];
        }else{
            return ['type'=>'success','msg'=>'预览成功','spu'=>$baseSpu];
        }
        
    }


  


    public function DelBaseSpu($params){
        $id = $params['id'];
        $base = Db::table('self_spu')->where('id',$id)->first();
        $log['name'] = $base->spu;
        $log['user_id'] =  $params['user_id'];
        $log['type'] = 4;
        $log['create_time'] = time();
        $res = Db::table('self_del_log')->insert($log);
        $base = Db::table('self_spu')->where('id',$id)->delete();
        return ['type'=>'success','msg'=>'删除成功'];
    }


    public function GetMarket($params){
        $base_spu_id = $params['base_spu_id'];
        $markets = Db::table('self_market')->get();
        foreach ($markets as $market) {
            # code...
            $market->is_repeat = false;
            $is_repeat = Db::table('self_spu')->where('market',$market->identifying)->where('base_spu_id',$base_spu_id)->first();
            if($is_repeat){
                $market->is_repeat = true;
            }
        }

        return [
            'msg'=>'获取成功',
            'type'=>'success',
            'data' => $markets,
        ];

    }



    //生成spu，预览
    public function SpuPreview($params){
        
        $posttype = $params['posttype']??1;
        //类型 1预览 2生成

        $query['platform_id'] = $params['platform_id'];
        $query['type'] = $params['type'];

        $platformres  =  Db::table('platform')->where('id',$query['platform_id'])->first();
        $platform = $platformres->identifying;

        if($query['type']==1){

            //基础spu
            $base_spu_id = $params['base_spu_id'];
            $cates =  Db::table('self_base_spu')->where('id', $base_spu_id)->first();
            if(!$cates){
                return ['type'=>'fail','msg'=>'不存在此基础spu,--'.$base_spu_id];
            }
            $query['base_spu_id'] = $base_spu_id;
            $query['one_cate_id'] = $cates->one_cate_id??0;
            $query['two_cate_id'] = $cates->two_cate_id??0;
            $query['three_cate_id'] = $cates->three_cate_id??0;
            $query['is_new'] = $cates->is_new??0;
            $query['num'] = $cates->num;
            //市场
            $markets = $params['market'];
            foreach ($markets  as $market) {
                # code...
                $query['market'] = $market;
                //正常spu 平台1位+大类2位+三类2位+编号五位
                $spus['spu'][]= $platform.$query['market'].$cates->base_spu;
            }

        }elseif($query['type']==2){

            $spures = Db::table('self_spu')->where('type',2)->orderby('num','desc')->first();

            //查询重复
            $group_spu_res = $params['group_spu'];

            foreach ($group_spu_res as &$v) {
                # code...
                $new_spu_res = Db::table('self_spu')->where('spu',$v)->orWhere('old_spu',$v)->first();
                $v = $new_spu_res->spu;
            }
            

            $spuresult = DB::select('select spu , count(group_spu)as count from self_group_spu group by spu  having count = ?', [count($group_spu_res)]);

            foreach ($spuresult as $sspu) {
                # code...
                $group_spu_result = DB::table('self_group_spu')->where('spu',$sspu->spu)->whereIn('group_spu',$group_spu_res)->get();

                if(count($group_spu_res)==count($group_spu_result)){
                    return ['type'=>'fail','msg'=>'生成组合spu失败,已有同样组合--'.$sspu->spu];
                }
            }

   
            //查询编码
            if(!$spures){
                //1000开始
                $num = 1;
            }else{
                $num = $spures->num+1;
            }

            $query['num'] = str_pad($num, 5, 0, STR_PAD_LEFT);
            $spus['spu']= $platform.'ZUHE'.$query['num'];
            $spus['num']= $query['num'];

        }
        if($posttype==1){
            return ['type'=>'success','msg'=>$spus['spu']];
        }else{
            db::beginTransaction();//开启事务
            //是否新品
            $query['user_id'] = $params['user_id']??'';
            $query['create_time'] = time();
            $query['status'] = 1;
            $spu_insert['user_id'] = $params['user_id']??'';
            $spu_insert['create_time'] = time();
            $spu_insert['spu'] = $spus['spu'];

            if(isset($params['content'])){
                $query['content'] = $params['content'];
            }

            if($query['type']==1){
                foreach ($spus['spu'] as $vp) {
                    # code...
                    if($vp){
                        $query['base_spu_id'] = $base_spu_id;
                        $query['spu'] = $vp;

                        //插入spu表
                        $res = Db::table('self_spu')->insert($query);
                        if(!$res){
                            return ['type'=>'fail','msg'=>'生成失败'];
                        }
                    }
                }

            }else{
                $query['spu'] = $spus['spu'];
                $childSpu = $params['group_spu'][0] ?? '';
                $childSpuMdl = db::table('self_spu')
                    ->where('spu', $childSpu)
                    ->orWhere('old_spu', $childSpu)
                    ->first();
                if (empty($childSpuMdl)){
                    return ['type'=>'fail','msg'=>'spu数据不存在！'];
                }
                $query['one_cate_id'] = $childSpuMdl->one_cate_id;
                $query['two_cate_id'] = $childSpuMdl->two_cate_id;
                $query['three_cate_id'] = $childSpuMdl->three_cate_id;
                //插入spu表
                $gspu_id = Db::table('self_spu')->insertGetid($query);

                if(!$gspu_id){
                    return ['type'=>'fail','msg'=>'生成失败'];
                }

                $i['base_spu'] = $query['spu'];
                $i['user_id'] =$query['user_id'];
                $i['create_time'] = $query['create_time'];
                $i['is_new'] = 2;
                $i['one_cate_id'] =0;
                $i['two_cate_id'] = 0;
                $i['three_cate_id'] = 0;
                $i['status'] = 1;
                $i['num'] = 0;
                $base_spu_id = db::table('self_base_spu')->insertGetId($i);
                db::table('self_spu')->where('id',$gspu_id)->update(['base_spu_id'=>$base_spu_id]);
  
            }



            // if(isset($params['copy_spu'])){
            //     $new_spu = $this->GetNewSpu($params['copy_spu']);
            //     $spu_color =  Db::table('self_spu_color')->where('spu',$new_spu)->get();
            //     if(!empty($spu_color)){
            //         foreach ($spu_color as $sp){
            //             $copy = Db::table('self_spu_color')->insert(['spu'=>$spus['spu'],'color_id'=>$sp->color_id,'img'=>$sp->img,'user_id'=>$params['user_id']]);
            //             if(!$copy){
            //                 db::rollback();
            //                 return ['type'=>'fail','msg'=>'关联出错，请检查关联spu的数据情况'];
            //             }
            //         }
            //     }else{
            //         return ['type'=>'fail','msg'=>'此关联spu无颜色数据'];
            //     }
            // }

            if($query['type']==2){
                //如果是组合spu，还需要插入组合spu-库存sku表,以及生成库存sku
                
                $query['one_cate_id'] = 0;
                $query['two_cate_id'] = 0;
                $query['three_cate_id'] = 0;
                $query['is_new'] = 0;
                //市场
                $query['market'] = '';
                $group_spu_res = $params['group_spu'];

                foreach ($group_spu_res as $v) {
                    //获取库存sku详情
                    // $res = $this->GetCustomSku($v);
                    // $spu_insert['custom_sku'] = $v; 
                    $group_new_spu_res = Db::table('self_spu')->where('spu',$v)->orWhere('old_spu',$v)->first();
                    
                    $group_new_spu = $group_new_spu_res->spu;
                    $res = Db::table('self_group_spu')->insert(['spu'=>$spus['spu'],'spu_id'=>$gspu_id,'group_spu'=>$group_new_spu,'group_spu_id'=>$group_new_spu_res->id,'create_time'=>$spu_insert['create_time'],'user_id'=>$query['user_id']]);
                    if(!$res){
                        return ['type'=>'fail','msg'=>'生成组合spu失败'];
                    }
                }
            }
            db::commit();
            return ['type'=>'success','msg'=>'生成成功','spu'=>$spus['spu']];
        }
        
        
    }


      //生成spu，预览
      public function SpuPreviewb($params){
        
        $posttype = $params['posttype']??1;
        //类型 1预览 2生成

        $query['platform_id'] = $params['platform_id'];
        $query['one_cate_id'] = $params['one_cate_id']??'';
        $query['two_cate_id'] = $params['two_cate_id']??'';
        $query['three_cate_id'] = $params['three_cate_id']??'';
        $query['type'] = 1;

        $platformres  =  Db::table('platform')->where('id',$query['platform_id'])->first();
        $platform = $platformres->identifying;

        if($query['type']==1){

            $one_cateres   =  Db::table('self_category')->where('id',$query['one_cate_id'])->first();
            $one_cate = $one_cateres->identifying;

            // $two_cateres   =  Db::table('self_category')->where('id',$query['two_cate_id'])->first();
            // $two_cate = $two_cateres->identifying;

            $three_cateres   =  Db::table('self_category')->where('id',$query['three_cate_id'])->first();
            $three_cate = $three_cateres->identifying;
            //正常spu
            $spures = Db::table('self_spu')->where('type',3)->where('platform_id',$query['platform_id'])->orderby('id','desc')->first();
            //查询编码
            if(!$spures){
                //1000开始
                $num = 1;
            }else{
                $num = $spures->num+1;
            }

            //补足五位
            $query['num'] = str_pad($num, 5, 0, STR_PAD_LEFT);
            
            //正常spu 平台1位+大类2位+三类2位+编号五位
            $spus['spu']= $platform.$one_cate.$three_cate.$query['num'];
            $spus['num']= $query['num'];

        }
        
        $query['user_id'] = $params['user_id']??'';
        $query['create_time'] = time();
        $query['status'] = 1;
        $spu_insert['user_id'] = $params['user_id']??'';
        $spu_insert['create_time'] = time();
        $spu_insert['spu'] = $spus['spu'];
        $query['spu'] = $spus['spu'];
        $query['num'] = $spus['num'];
        if(isset($params['content'])){
            $query['content'] = $params['content'];
        }
        //插入spu表
        $res = Db::table('self_spu')->insert($query);
        if(!$res){
            return ['type'=>'fail','msg'=>'生成失败'];
        }

        return ['type'=>'success','msg'=>'生成成功','spu'=>$spus['spu']];
        
    }


    public function SpuUpdate($params){
        $id = $params['id'];
        $add['content'] = $params['content']??'';
        // if(isset($params['operate_user_id'])){
          
        // }
        $add['operate_user_id'] = $params['operate_user_id']??0;
        $updateresult = Db::table('self_spu')->where('id',$id)->update($add);

        if($updateresult){
            return ['type'=>'success','msg'=>'修改成功'];
        }
    }


    //spu删除
    public function SpuDel($params){

        $id = $params['id'];

        $spures = Db::table('self_spu')->where('id',$id)->first();
        if($spures->type==2){
            Db::table('self_group_spu')->where('spu',$spures->spu)->orwhere('spu',$spures->old_spu)->delete();
        }
        Db::table('self_custom_sku')->where('spu_id',$id)->delete();
        Db::table('self_sku')->where('spu_id',$id)->delete();

        $del['user_id'] = $params['user_id']??'';

        //加入删除日志  type 1 spu 2custom_sku 3sku
        $log['id'] =$id;
        $log['user_id'] =  $del['user_id'];
        $log['type'] = 1;
        $logs = $this->DelLog($log);

        //删除
        $delresult = Db::table('self_spu')->where('id',$id)->delete();

        if(!$delresult||!$logs){
            return ['type'=>'fail','msg'=>'删除失败'];
        }
        return ['type'=>'success','msg'=>'删除成功'];
    }


    //asin获取库存sku
    public function AsinGetCustomSkuM($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }
        $list = db::table('self_sku as a')->leftjoin('self_custom_sku as b','a.custom_sku_id','=','b.id');
        if(isset($params['asin'])){
            $asin = $params['asin'];
            if(is_array($asin)){
                $list = $list->whereIn('asin',$asin);
            }else{
                $list = $list->where('asin',$asin);
            }

        }
        $totalNum =  $list->count();
        $list = $list->offset($page)->limit($limit)->select('a.asin','a.fasin','a.sku','a.old_sku','a.sku as sku_id','a.spu','a.spu_id','b.custom_sku','b.old_custom_sku','b.id as custom_sku_id')->get();
        
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];
    }



    //spu列表-组合spu
    public function SpuListByzuhe($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }
        $posttype = $params['posttype']??1;
        $where['status'] = 1;


        if(isset($params['user_id'])){
            $where['user_id'] = $params['user_id'];
        }

        $list = Db::table('self_spu')->where('type',2);
        if(isset($params['start_time'])&&isset($params['end_time'])){
            $start_time = strtotime($params['start_time']);
            $end_time = strtotime($params['end_time']); 
            $list = $list->whereBetween('create_time', [$start_time, $end_time]);
        }

        if(isset($params['spu'])){

            $spus = [];

            $spus_a = Db::table('self_spu')->where('spu','like','%'.$params['spu'].'%')->orWhere('old_spu','like','%'.$params['spu'].'%')->select('spu')->get()->toArray();
            $spus_b = Db::table('self_group_spu as a')->leftjoin('self_spu as b','a.group_spu_id','=','b.id')->where('b.spu','like','%'.$params['spu'].'%')->orwhere('b.old_spu','like','%'.$params['spu'].'%')->select('a.spu')->get()->toArray();
            $spus_a = array_column( $spus_a,'spu');
            $spus_b = array_column($spus_b,'spu');
            $spus = array_merge($spus_a, $spus_b);
            $list = $list->whereIn('spu',$spus);
        }
        $totalNum =  $list ->where($where)->count();
        $list = $list->where($where)
                ->offset($page)
                ->limit($limit)
                ->orderBy('id','desc')
                ->select('id','user_id','spu','old_spu','create_time','base_spu_id', 'market')
                ->get();

        // var_dump($list);
        // exit;
                
        foreach ($list as $v) {
            if(!$v->old_spu){
                $v->old_spu = $v->spu;
            }
            //sku合计
            $v->custom_sku_count = Db::table('self_custom_sku')->where('spu_id',$v->id)->count();
            $v->sku_count = Db::table('self_sku')->where('spu_id',$v->id)->count();
            //用户名
            $v->account = '';
            $users = $this->GetUsers($v->user_id);
            if($users){
                $v->account = $users['account'];
            }

            //子spu
            $group_spus = Db::table('self_group_spu')->where('spu_id',$v->id)->select('group_spu_id')->get()->toArray();

            $group_spus = array_column($group_spus,'group_spu_id');

            foreach ($group_spus  as&$sv) {
                $osp =  Db::table('self_spu')->where('id',$sv)->first();
                if($osp){
                    if($osp->old_spu){
                        $sv = $osp->old_spu;
                    }else{
                        $sv = $osp->spu;
                    }
                }
                # code...
            }
            
            $v->img = '';



            $v->group_spus = implode(',',$group_spus);


            //创建者
            $v->user = '';
            $users = $this->GetUsers($v->user_id);
            if($users){
                $v->user = $users['account'];
            }
            
            $v->create_time = date('Y-m-d H:i:s',$v->create_time);
            $v->market_name = '';
            $market = db::table('self_market')->where('identifying',$v->market)->first();
            if($market){
                $v->market_name = $market->name;
            }

        }


        if($posttype==2){
            $p['title']='组合spu列表'.time();
            $p['title_list']  = [
                'spu'=>'spu',
                'user'=>'创建者',
                'custom_sku_count'=>'库存sku合计',
                'sku_count'=>'sku合计',
                'group_spus'=>'子spu合集',
            ];

            // $this->excel_expord($p);
                
            $p['data'] =   $list;
            $p['user_id'] = Db::table('users')->where('token',$params['token'])->first()->Id;
            $p['type'] = 'spu表-导出';
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }



   
            
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];

    }


      //基础spu列表
      public function SpuListByBase($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }
        $posttype = $params['posttype']??1;


        if(isset($params['one_cate_id'])){
            $where['one_cate_id'] = $params['one_cate_id'];
        }
        if(isset($params['two_cate_id'])){
            $where['two_cate_id'] = $params['two_cate_id'];
        }
        if(isset($params['three_cate_id'])){
            $where['three_cate_id'] = $params['three_cate_id'];
        }
        if(isset($params['user_id'])){
            $where['user_id'] = $params['user_id'];
        }
        if(isset($params['base_spu_id'])){
            $where['id'] = $params['base_spu_id'];
        }


        $list = Db::table('self_spu');
        if(isset($params['start_time'])&&isset($params['end_time'])){
            $start_time = strtotime($params['start_time']);
            $end_time = strtotime($params['end_time']); 
            $list = $list->whereBetween('create_time', [$start_time, $end_time]);
        }

        if(isset($params['base_spu'])){
            $list = $list->where(function($query) use($params){
                $query->where('spu','like','%'.$params['base_spu'].'%')
                    ->orwhere('old_spu','like','%'.$params['base_spu'].'%');
            });
        }


        if(isset($params['color_style'])){
            $list = $list->where('color_style','=',$params['color_style']);
        }

        if(isset($params['seasonal_style'])){
            $list = $list->where('seasonal_style','=',$params['seasonal_style']);
        }

        // 面料成分
        if(isset($params['fabric_composition'])){
            $list = $list->where('fabric_composition', 'like', '%'.$params['fabric_composition'].'%');
        }
          if(isset($params['class'])){
              $list = $list->where('class', $params['class']);
          }

        if(!empty($where)){
            $list = $list ->where($where);
        }
        $totalNum =  $list ->count();
        $list = $list->offset($page)
                ->limit($limit)
                ->orderBy('id','desc')
                ->get();
                

        foreach ($list as $v) {
            $v->spu_color = Db::table('self_spu_color')->where('base_spu_id',$v->id)->count();
            $v->spu_size = Db::table('self_spu_size')->where('base_spu_id',$v->id)->count();
            //用户名
            $v->account = '';
            $users = $this->GetUsers($v->user_id);
            if($users){
                $v->account = $users['account'];
            }

            //大类
            $v->one_cate = '';
            $one_cate = $this->GetCategory($v->one_cate_id);
            if($one_cate){
                $v->one_cate = $one_cate['name'];
            }

            //二类
            $v->two_cate = '';
            $two_cate = $this->GetCategory($v->two_cate_id);
            if($two_cate){
                $v->two_cate = $two_cate['name'];
            }

            //三类
            $v->three_cate = '';
            $three_cate = $this->GetCategory($v->three_cate_id);
            if($three_cate){
                $v->three_cate = $three_cate['name'];
            }

            $v->create_time = date('Y-m-d H:i:s',$v->create_time);

            $v->img = '';
            $v->img = $this->GetBaseSpuImg($v->id);
            if ($v->class == 1){
                $v->class_name = '自主研发款';
            }else if ($v->class == 2){
                $v->class_name = '线上采购款';
            }else{
                $v->class_name = '';
            }
        }

        // if($posttype==2){
        //     $this->ExcelSpu($list);
        // }

        if($posttype==2){
                  
            $p['title']='基础spu表'.time();

            $listtlt = [
                'base_spu'=>'spu',
                'old_base_spu'=>'旧spu',
                'one_cate'=>'大类',
                'two_cate'=>'二类',
                'three_cate'=>'三类',
                'class_name'=>'分类',
                'fabric_composition'=>'面料成分',
                'content'=>'备注',
                'account'=>'创建者',
                'create_time'=>'创建时间',
            ];

    
            $p['title_list']  = $listtlt;
            $p['data'] =   $list;
            $p['user_id'] = Db::table('users')->where('token',$params['token'])->first()->Id;
            $p['type'] = '基础spu表-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
            // $this->ExcelSku($list);
        }
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];

    }

    //基础spu列表
    public function SpuList($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 100;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }
        $posttype = $params['posttype']??1;


        if(isset($params['one_cate_id'])){
            $where['one_cate_id'] = $params['one_cate_id'];
        }
        if(isset($params['two_cate_id'])){
            $where['two_cate_id'] = $params['two_cate_id'];
        }
        if(isset($params['three_cate_id'])){
            $where['three_cate_id'] = $params['three_cate_id'];
        }
        if(isset($params['user_id'])){
            $where['user_id'] = $params['user_id'];
        }
        if(isset($params['base_spu_id'])){
            $where['id'] = $params['base_spu_id'];
        }


        $list = Db::table('self_spu');
        if(isset($params['start_time'])&&isset($params['end_time'])){
            $start_time = strtotime($params['start_time']);
            $end_time = strtotime($params['end_time']); 
            $list = $list->whereBetween('create_time', [$start_time, $end_time]);
        }

        if(isset($params['base_spu'])){
            $list = $list->where(function($query) use($params){
                $query->where('spu','like','%'.$params['base_spu'].'%')
                    ->orwhere('old_spu','like','%'.$params['base_spu'].'%');
            });
        }


        if(isset($params['spu'])){
            $list = $list->where(function($query) use($params){
                $query->where('spu','like','%'.$params['spu'].'%')
                    ->orwhere('old_spu','like','%'.$params['spu'].'%');
            });
        }


        if(isset($params['color_style'])){
            $list = $list->where('color_style','=',$params['color_style']);
        }

        if(isset($params['seasonal_style'])){
            $list = $list->where('seasonal_style','=',$params['seasonal_style']);
        }

        // 面料成分
        if(isset($params['fabric_composition'])){
            $list = $list->where('fabric_composition', 'like', '%'.$params['fabric_composition'].'%');
        }
          if(isset($params['class'])){
              $list = $list->where('class', $params['class']);
          }

        if(!empty($where)){
            $list = $list ->where($where);
        }
        $totalNum =  $list ->count();
        $list = $list->offset($page)
                ->limit($limit)
                ->orderBy('id','desc')
                ->get();
                

        foreach ($list as $v) {
            $v->base_spu_id = $v->id;
            $v->spu_color = Db::table('self_spu_color')->where('base_spu_id',$v->id)->count();
            $v->spu_size = Db::table('self_spu_size')->where('base_spu_id',$v->id)->count();
            //用户名
            $v->account = '';
            $users = $this->GetUsers($v->user_id);
            if($users){
                $v->account = $users['account'];
            }

            //大类
            $v->one_cate = '';
            $one_cate = $this->GetCategory($v->one_cate_id);
            if($one_cate){
                $v->one_cate = $one_cate['name'];
            }

            //二类
            $v->two_cate = '';
            $two_cate = $this->GetCategory($v->two_cate_id);
            if($two_cate){
                $v->two_cate = $two_cate['name'];
            }

            //三类
            $v->three_cate = '';
            $three_cate = $this->GetCategory($v->three_cate_id);
            if($three_cate){
                $v->three_cate = $three_cate['name'];
            }

            $v->create_time = date('Y-m-d H:i:s',$v->create_time);

            $v->img = '';
            $v->img = $this->GetBaseSpuImg($v->id);
            if ($v->class == 1){
                $v->class_name = '自主研发款';
            }else if ($v->class == 2){
                $v->class_name = '线上采购款';
            }else{
                $v->class_name = '';
            }
        }

        // if($posttype==2){
        //     $this->ExcelSpu($list);
        // }

        if($posttype==2){
                  
            $p['title']='基础spu表'.time();

            $listtlt = [
                'base_spu'=>'spu',
                'old_base_spu'=>'旧spu',
                'one_cate'=>'大类',
                'two_cate'=>'二类',
                'three_cate'=>'三类',
                'account'=>'创建者',
            ];

    
            $p['title_list']  = $listtlt;
            $p['data'] =   $list;
            $p['user_id'] = Db::table('users')->where('token',$params['token'])->first()->Id;
            $p['type'] = '基础spu表-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
            // $this->ExcelSku($list);
        }
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];

    }


    //spu列表
    public function SpuList_old($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }
        $posttype = $params['posttype']??1;
        $where['a.status'] = 1;

        if(isset($params['one_cate_id'])){
            $where['b.one_cate_id'] = $params['one_cate_id'];
        }
        if(isset($params['two_cate_id'])){
            $where['b.two_cate_id'] = $params['two_cate_id'];
        }
        if(isset($params['three_cate_id'])){
            $where['b.three_cate_id'] = $params['three_cate_id'];
        }
        if(isset($params['platform_id'])){
            $where['a.platform_id'] = $params['platform_id'];
        }

        if(isset($params['operate_user_id'])){
            $where['a.operate_user_id'] = $params['operate_user_id'];
        }

        if(isset($params['supply_user_id'])){
            $where['supply_user_id'] = $params['supply_user_id'];
        }

        if(isset($params['user_id'])){
            $where['b.user_id'] = $params['user_id'];
        }

        if(isset($params['type'])){
            $where['a.type'] = $params['type'];
        }





       


        $list =  Db::table('self_spu as a')->leftjoin('self_base_spu as b','a.base_spu_id','=','b.id');
        if(isset($params['start_time'])&&isset($params['end_time'])){
            $start_time = strtotime($params['start_time']);
            $end_time = strtotime($params['end_time']); 
            $list = $list->whereBetween('b.create_time', [$start_time, $end_time]);
        }

        if(isset($params['spu'])){
            // $list = $list->where('spu','like','%'.$params['spu'].'%');
            // $list = $list->orwhere('old_spu','like','%'.$params['spu'].'%');
            $list = $list->where(function($query) use($params){
                $query->where('a.spu','like','%'.$params['spu'].'%')
                    ->orwhere('a.old_spu','like','%'.$params['spu'].'%');
            });
        }

        if(isset($params['spu_status']) && is_array($params['spu_status'])){
            $list = $list->whereIn('a.spu_status', $params['spu_status']);
        }

        if(isset($params['color_style'])){
            $list = $list->where('b.color_style','=',$params['color_style']);
        }

        if(isset($params['seasonal_style'])){
            $list = $list->where('b.seasonal_style','=',$params['seasonal_style']);
        }

        // 面料成分
        if(isset($params['fabric_composition'])){
            $list = $list->where('b.fabric_composition', 'like', '%'.$params['fabric_composition'].'%');
        }
        $totalNum =  $list ->where($where)->count();
        $list = $list->where($where)
            ->offset($page)
            ->limit($limit)
            ->select('a.*','b.one_cate_id','b.two_cate_id','b.three_cate_id','b.user_id','b.create_time','b.seasonal_style','b.color_style','a.market', 'b.fabric_composition','b.class')
            ->orderBy('a.id','desc')
            ->get();

        foreach ($list as $v) {
            //sku合计
            $v->custom_sku_count = Db::table('self_custom_sku')->where('spu_id',$v->id)->count();
            $v->sku_count = Db::table('self_sku')->where('spu_id',$v->id)->count();
            //用户名
            $v->account = '';
            $users = $this->GetUsers($v->user_id);
            if($users){
                $v->account = $users['account'];
            }

            //所属spu合计
            if($v->type==2){
                $v->spu_color = '-';
            }else{
                $v->spu_color = Db::table('self_spu_color')->where('base_spu_id',$v->base_spu_id)->count();
                $v->spu_size = Db::table('self_spu_size')->where('base_spu_id',$v->base_spu_id)->count();
            }

            //运营负责人
            $v->operate_user = '';
            $operate_users = $this->GetUsers($v->operate_user_id);
            if($operate_users){
                $v->operate_user = $operate_users['account'];
            }

            //创建者
            $v->user = '';
            $users = $this->GetUsers($v->user_id);
            if($users){
                $v->user = $users['account'];
            }
            
             //供应链负责人
            $v->supply_user = '';
            $supply_users = $this->GetUsers($v->supply_user_id);
            if($supply_users){
                $v->supply_user = $supply_users['account'];
            }

            //大类
            $v->one_cate = '';
            $one_cate = $this->GetCategory($v->one_cate_id);
            if($one_cate){
                $v->one_cate = $one_cate['name'];
            }

            //二类
            $v->two_cate = '';
            $two_cate = $this->GetCategory($v->two_cate_id);
            if($two_cate){
                $v->two_cate = $two_cate['name'];
            }

            //三类
            $v->three_cate = '';
            $three_cate = $this->GetCategory($v->three_cate_id);
            if($three_cate){
                $v->three_cate = $three_cate['name'];
            }

            //平台
            $v->platform = '';
            $platform = $this->GetPlatform($v->platform_id);
            if($platform){
                $v->platform = $platform['name'];
            }

            $v->create_time = date('Y-m-d H:i:s',$v->create_time);


            $v->img = '';
            $v->img = $this->GetBaseSpuImg($v->base_spu_id);

            $spu_shops = Redis::Hget('datacache:spushop',$v->id);
            if($spu_shops){
                $spu_shops = json_decode($spu_shops);
            }else{
                $shops = Db::table('self_sku')->where('spu_id',$v->id)->groupby('shop_id')->get();
                $spu_shops = [];
                foreach ($shops as $sv) {
                    # code...
                    $shopres = $this->GetShop($sv->shop_id);
                    if($shopres){
                        $shopone['shop_id'] =  $shopres['Id'];
                        $shopone['shop_name'] =  $shopres['shop_name'];
                        $spu_shops[] = $shopone;
                    }
                }
                if($spu_shops){
                    Redis::Hset('datacache:spushop',$v->id,json_encode($spu_shops));
                }
            }
            $v->spu_shops = $spu_shops;

            $v->shop_name = '';

            // $v->shop_name = $this->GetShop($v->shop_id)['shop_name'];
            $v->seasonal_style_e = '';
            //1.夏季款 2.冬季款 3.四季款
            if($v->seasonal_style==1){
                $v->seasonal_style_e = '夏季款';
            }else if($v->seasonal_style==2){
                $v->seasonal_style_e = '冬季款';
            }else if($v->seasonal_style==3){
                $v->seasonal_style_e = '四季款';
            }

            $v->color_style_e = '';
            if($v->color_style==1){
                $v->color_style_e = '纯色';
            }else if($v->color_style==2){
                $v->color_style_e = '印花';
            }

            $v->market_name = '';
            $market = db::table('self_market')->where('identifying',$v->market)->first();
            if($market){
                $v->market_name = $market->name;
            }
            $v->spu_status_name = Constant::SPU_STATUS[$v->spu_status] ?? '';
        }

        // if($posttype==2){
        //     $this->ExcelSpu($list);
        // }

        if($posttype==2){
                  
            $p['title']='spu表'.time();

            $listtlt = [
                'spu'=>'spu',
                'old_spu'=>'旧spu',
                'img' => '图片',
                'custom_sku_count'=>'库存sku数量',
                'sku_count'=>'销售sku数量',
                'platform'=>'平台',
                'market'=>'国家标识',
                'seasonal_style_e'=>'四季款',
                'color_style_e'=>'款式',
                'one_cate'=>'大类',
                'two_cate'=>'二类',
                'three_cate'=>'三类',
                'operate_user'=>'产品负责人',
                'supply_user'=>'供应链负责人',
                'user'=>'创建者',
            ];

    
            $p['title_list']  = $listtlt;
            $p['data'] =   $list;
            $p['user_id'] = Db::table('users')->where('token',$params['token'])->first()->Id;
            $p['type'] = 'spu表-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
            // $this->ExcelSku($list);
        }
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];

    }

    public function SpuSelect($params){
        $spu = DB::table('self_spu');
        if(isset($params['spu'])){
            $spu = $spu->where('spu','like','%'.$params['spu'].'%');
            $spu = $spu->orWhere('old_spu','like','%'.$params['spu'].'%');
        }
        $spu = $spu->select('id','spu','old_spu')->get()->toArray();

        return [
            'data' => $spu
        ];
    }

    public function GetGroupSpu($params){
        $spu = $params['spu'];
        $res = Db::table('self_group_spu')->where('spu',$spu)->select('group_spu')->get();
        return[
            'data'=>$res,
        ];
    }

    public function ZuheSpuList($params){
        $spu = $params['spu'];
        $spus = $this->GetSpus($spu);
        $res = Db::table('self_group_spu')->whereIn('spu',$spus)->select('group_spu')->get();
        foreach ($res as $key => $group_spu) {
            # code...
            $group_spus = $this->GetSpus($group_spu->group_spu);
            $custom_sku_colors = Db::table('self_custom_sku as a')
                ->leftjoin('self_color_size as b','a.color','=','b.identifying')
                ->leftJoin('self_spu_color as c', function ($j){
                    return $j->on('a.base_spu_id', '=', 'c.base_spu_id')
                        ->on('b.id', '=', 'c.color_id');
                })
                ->whereIn('a.spu',$group_spus)
                ->select('a.color','b.id','b.name','b.english_name','c.img')
                ->groupBy('a.color')
                ->get();
            $res[$key]->colors =  $custom_sku_colors;
            $res[$key]->group_spu = $group_spus[1]??$group_spus[0];
            $res[$key]->group_spus = $group_spus;
        }
        return['type'=>'success','data'=>$res];
    }

    //组合spu-库存sku生成
    public function ZuheSkuPreview($params){

        //组合spu
        $spu_id = $params['spu_id'];
        //尺码组合
        $sizes = $params['sizes'];
        //spu成员
        $group_spu = $params['group_spu'];

        $new_spu = $this->GetSpu($spu_id);
        $cusres = array(); //新库存sku相关信息
        $err = [];
        foreach ($sizes as $size) {
            //一个尺码生成一个新的库存sku
            $cusres[$size]['color'] = '';
            foreach ($group_spu as $spures) {
                # code...
                //成员spu
                $spu = $spures['spu'];
                $spuid = $this->GetSpuId($spu);
                //颜色
                $colors = $spures['colors'];

                foreach ($colors as $color) {
                    # code...
                    // $color = $this->GetColorSize($colorid);
                    //单个库存sku
                    $custom_sku = DB::table('self_custom_sku')->where('spu_id',$spuid)->where('color',$color)->where('size',$size)->first();
                    if(!$custom_sku){
                        return ['type'=>'fail','msg'=>'不存在此颜色尺码的库存sku,spu:'.$spu.'|color:'.$color.'|size:'.$size];
                    }
                    //将旧sku存进数组
                    $cusres[$size]['old_custom_sku'][] = $custom_sku->custom_sku;

                    $colorData = DB::table('self_color_size')->where('identifying',$color)->select('name')->first();
                    //中文名
                    $colorName[] = $colorData->name;
                }

                $colorStr = implode(",",$colors);
                $self_color_size = DB::table('self_color_size')->where('color_son',$colorStr)->select('id','identifying')->first();
                if($self_color_size){
                    $cusres[$size]['color'] = $self_color_size->identifying;
                }else{
                    $max_color_size = DB::table('self_color_size')->where('color_class','Z')->select('class_num')->orderBy('class_num','desc')->first();
                    $insertColor['name'] = implode("+",$colorName);
                    $insertColor['identifying'] = 'Z'.$max_color_size->class_num;
                    $insertColor['user_id'] = 1;
                    $insertColor['status'] = 1;
                    $insertColor['type'] = 1;
                    $insertColor['create_time'] = time();
                    $insertColor['english_name'] = 'assembly'.$max_color_size->class_num;
                    $insertColor['color_class'] = 'Z';
                    $insertColor['class_num'] = $max_color_size->class_num+1;
                    $insertColor['color_son'] = $colorStr;
                    $insert_c_i = DB::table('self_color_size')->insert($insertColor);
                    if(!$insert_c_i){
                        return ['type'=>'fail','msg'=>'新增组合色系失败:'.$colorStr];
                    }else{
                        $cusres[$size]['color'] = $insertColor['identifying'];
                    }
                }

            }


            //新库存sku spu+颜色+尺码
            $cusres[$size]['custom_sku'] =  $new_spu['spu'].'-'.$cusres[$size]['color'].'-'.$size;
//            var_dump($cusres[$size]);
            //  查询重复
             $group_cus_res = $cusres[$size]['old_custom_sku'];

             $cusresult = DB::select('select custom_sku , count(group_custom_sku)as count from self_group_custom_sku group by custom_sku  having count = ?', [count($group_cus_res)]);
             $is_group_repeat = true;
             foreach ($cusresult as $cccus) {
                 # code...
                 $group_cus_result = DB::table('self_group_custom_sku')->where('custom_sku',$cccus->custom_sku)->whereIn('group_custom_sku',$group_cus_res)->get();
 

                 if(count($group_cus_res)==count($group_cus_result)){
                    // $cusres[$size]['custom_sku'] = $cccus->custom_sku;
                    //  return ['type'=>'fail','msg'=>'生成组合sku失败,已有同样组合--'.$cccus->custom_sku];

                    if(!isset($params['shop_id'])){
                        return ['type'=>'fail','msg'=>'生成组合sku失败,已有同样组合--'.$cccus->custom_sku];
                    }else{
                        $is_group_repeat = false;
                        $cusres[$size]['custom_sku'] = $cccus->custom_sku;
                    }
                 }
             }
 


            $insert = [];
            //存入self_custom_sku表
            //查询是否存在
            $is_repeat =  DB::table('self_custom_sku')->where('custom_sku',$cusres[$size]['custom_sku'])->first();
            if(!$is_repeat&&$is_group_repeat){
                //存入 self_custom_sku 表
                $insert['custom_sku'] = $cusres[$size]['custom_sku'];
                $insert['user_id'] = $params['user_id']??1;
                $insert['spu'] = $new_spu['spu'];
                $insert['color'] = $cusres[$size]['color'];
                $insert['size'] = $size;
                $insert['type'] = 2;
                $insert['spu_id'] = $spu_id;
                try {
                    $insert['create_time'] = time();
                    $insert['status'] = 1;
                    $custom_id = DB::table('self_custom_sku')->insertGetid($insert);
                } catch (\Throwable $th) {
                    return ['type'=>'fail','msg'=>$th->getMessage().'line:'.$th->getLine()];
                }
             
                //存入self_group_custom_sku表
                foreach ($cusres[$size]['old_custom_sku'] as $group_custom_sku) {
                    $group_is_repeat =  DB::table('self_group_custom_sku')->where('custom_sku',$cusres[$size]['custom_sku'])->where('group_custom_sku',$group_custom_sku)->first();
                    if(!$group_is_repeat){
                        $groupinsert['custom_sku'] = $cusres[$size]['custom_sku'];
                        $groupinsert['custom_sku_id']  = $custom_id;
                        $groupinsert['group_custom_sku'] = $group_custom_sku;
                        $groupinsert['group_custom_sku_id'] = $this->GetCustomSkuId($group_custom_sku);
                        try {
                            DB::table('self_group_custom_sku')->insert($groupinsert);
                        } catch (\Throwable $th) {
                            return ['type'=>'fail','msg'=>$th->getMessage().'line:'.$th->getLine()];
                        }
                    }
                }

            }else{

                $custom_id = $is_repeat->id;
            }


            //如果有店铺id 则是销售sku
            if(isset($params['shop_id'])){
                $shop_res = $this->GetShop($params['shop_id']);
                $shop_identifying = $shop_res['identifying'];
                if(empty($shop_identifying)){
                    return ['type'=>'fail','msg'=>'该店铺没有标识，请添加后再尝试生成'];
                }
                $cusres[$size]['sku']  = $shop_identifying.$params['shop_id'].'-'.$cusres[$size]['custom_sku'];

                if(isset($params['special'])){
                    $cusres[$size]['sku']  = $shop_identifying.$params['shop_id'].'-'.$cusres[$size]['custom_sku'].'-'.$params['special'];
                }
                $sku_is_repeat =  DB::table('self_sku')->where('sku',$cusres[$size]['sku'])->first();

                if(!$sku_is_repeat){
                    //存入 self_sku 表
                    $skuinsert['custom_sku'] = $cusres[$size]['custom_sku'];
                    $skuinsert['custom_sku_id'] = $custom_id;
                    $skuinsert['user_id'] = $params['operate_user_id']??1;
                    $skuinsert['operate_user_id'] = $params['user_id']??1;
                    $skuinsert['spu'] = $new_spu['spu'];
                    $skuinsert['spu_id'] = $spu_id;
                    $skuinsert['sku'] = $cusres[$size]['sku'];
                    $skuinsert['shop_id'] = $params['shop_id'];
                    $skuinsert['create_time'] = time();
                    $skuinsert['status'] = 1;
                    try {
                        $insertid = DB::table('self_sku')->insertGetId($skuinsert);
                        //加入补货预警消化队列
                        Redis::Lpush('datacache:go-buhuo-one-list',$insertid );
                        $cusres[$size]['insertid'] = $insertid;
                    } catch (\Throwable $th) {

                        return ['type'=>'fail','msg'=>$th->getMessage().'line:'.$th->getLine()];
                    }
                }else{
                    $err[]['sku'] = $cusres[$size]['sku'];
                }

            }
            
  

        }   



        if(count($err)>0){
            return ['type'=>'fail','msg'=>'该sku已生成'.json_encode($err)];
        }

        return ['type'=>'success','data'=>$cusres];

    }


    //获取库存组合sku详情
    public function GetZuheCustomSku($params){
        $custom_sku = $params['custom_sku'];
        $res = DB::table('self_group_custom_sku')->where('custom_sku',$custom_sku)->get();
        return['type'=>'success','data'=>$res];
    }

    //修改库存sku名字
    public function UpdateZuheCustomSku($params){
        // $userMdl = db::table('users')->where('token', $params['token'])->first();
        // if (empty($userMdl)){
        //     return ['type'=>'fail','msg'=>'用户信息不存在！'];
        // }
        // $customSku = db::table('self_custom_sku as a')
        //     ->leftJoin('self_spu as b', 'a.spu_id', '=', 'b.id')
        //     ->leftJoin('self_category as c', 'b.one_cate_id', '=', 'c.Id')
        //     ->where('a.id', $params['id'])
        //     ->select('a.*', 'c.is_clothing')
        //     ->first();
        // if (empty($customSku)){
        //     return ['type'=>'fail','msg'=>'该sku数据不存在！'];
        // }
        // if ($userMdl->Id != $customSku->user_id){
        //     return ['type'=>'fail','msg'=>'非创建人不可修改！'];
        // }
        // if ($customSku->is_clothing == 1){
        //     $controller = new Controller();
        //     $power = $controller->powers(['user_id' => $userMdl->Id, 'identity' => ['update_custom_sku_name']]);
        //     if (!$power['update_custom_sku_name']){
        //         return ['type'=>'fail','msg'=>'服装类目您无修改权限！'];
        //     }
        // }

  
        if(isset($params['box_num'])){
            $add['box_num'] = $params['box_num'];
        }
        if(isset($params['length'])){
            $add['length'] = $params['length'];
        }
        if(isset($params['width'])){
            $add['width'] = $params['width'];
        }
        if(isset($params['height'])){
            $add['height'] = $params['height'];
        }
        if(isset($params['weight'])){
            $add['weight'] = $params['weight'];
        }

        if(isset($params['buy_price'])){
            $add['buy_price'] = $params['buy_price'];
        }
      
        $id = $params['id'];
        if(is_array($id)){
            $updateresult = Db::table('self_custom_sku')->whereIn('id',$id)->update($add);
        }else{
            $add['name'] = $params['name'];
            $updateresult = Db::table('self_custom_sku')->where('id',$id)->update($add);
        }
    
        if(!$updateresult){
            return ['type'=>'fail','msg'=>'修改失败'];
        }
        return ['type'=>'success','msg'=>'修改成功'];
    }

    public function SkuPreview($params){
        $spu_id = $params['spu_id'];
        if(isset($params['color_id'])){
            $color = $params['color_id'];
            if(!is_array($color)){
                $colors[0] = $color;
            }else{
                $colors = $color;
            }
        }
        $size = $params['size_id'];
        //是否有店铺id  有则同时生产库存sku+销售sku   无则只生成库存sku
        // begin 业务变更：可以多选商铺id
        $shop_ids = $params['shop_id']??'';
        $special = $params['special']??'';

        if(!empty($shop_ids)){
            //类型 1库存sku 2销售sku
            $type = 2;
        }else{
            $type = 1;
        }

        if(!is_array($size)){
            $sizes[0] = $size;
        }else{
            $sizes = $size;
        }

        $skulist = array();
        $res['type'] = $type;

        $i = 0;

        //获取spu信息
        $spures = $this->GetSpu($spu_id);
        $new_spu = $spures['spu'];
        if($spures['old_spu']){
            $spures['spu'] =  $spures['old_spu'];
        }
        if($spures['type']==2){
            return ['type'=>'fail','msg'=>'组合sku请用组合sku生成方法'];
            // foreach ($sizes as $sv) {
            //     # code...
            //     //获取尺寸信息
            //     $sizeres = $this->GetColorSize($sv);
            //     if(!$sizeres){
            //         return ['type'=>'fail','msg'=>'尺码不存在'];
            //     }

            //     if(!$spures){
            //         return ['type'=>'fail','msg'=>'spu不存在'];
            //     }
            //     //中文名
            //     //中文名 = 大类+小类+编号+颜色+尺码
            //     //第一步，获取该组合spu下的所有sku
            //     $spu = Db::table('self_spu')->where('spu',$spures['spu'])->orwhere('old_spu',$spures['spu'])->first();
            //     if($spu){
            //         $custom_sku_res = Db::table('self_group_spu')->where('spu',$spu->spu)->orwhere('spu',$spu->old_spu)->get();
            //     }else{
            //         $custom_sku_res = Db::table('self_group_spu')->where('spu',$spures['spu'])->get();
            //     }
            //     if(!$custom_sku_res){
            //         return ['type'=>'fail','msg'=>'成员库存sku的父级spu不存在'];
            //     }

            //     $custom_sku_list = array();
            //     foreach ($custom_sku_res as $v) {
            //         # code...
            //         //第二步，获取每个库存sku的spu
            //         $customres = $this->GetCustomSkus($v->custom_sku);
            //         $spu = $customres['spu'];
            //         $custom_sku_spulist[$spu] = $customres;
            //         $color_identifying = $customres['color'];
            //         $father_spu =Db::table('self_spu')->where('spu',$spu)->orwhere('old_spu',$spu)->first();
            //         //获取大类
            //         $one_cate= $this->GetCategory($father_spu->one_cate_id);

            //         //获取小类
            //         $three_cate=  $this->GetCategory($father_spu->three_cate_id);
            //         if(!$one_cate){
            //             return ['type'=>'fail','msg'=>'spu大类不存在'];
            //         }
            //         if(!$three_cate){
            //             return ['type'=>'fail','msg'=>'spu小类不存在'];
            //         }

            //         $num = str_pad($father_spu->num, 5, 0, STR_PAD_LEFT);
            //         //获取颜色
            //         $colors = Db::table('self_color_size')->where('identifying',$customres['color'])->first();
            //         $color = $customres['color'];
            //         if($colors){
            //             $color = $colors->name;
            //         }
            //         $sun_name = $one_cate['name'].$three_cate['name'].$num.$color.$sizeres['name'];
            //         $sunnames['spu_name']= $one_cate['name'].$three_cate['name'];
            //         $sunnames['num'] = $num;
            //         $sunnames['color'] = $color;
            //         $sunnames['size'] = $sizeres['name'];
            //         $sunnames['name'] = $sun_name;
            //         //各个颜色只取一个名字
            //         $custom_sku_list[$color_identifying] = $sunnames;
            //     }


            //     $custom_sku_spulist = array();
            //     // $si = 0;
            //     foreach ($custom_sku_list as $v) {
            //         # code...
            //         //将所有名字拼接
            //         $spu_name = $v['spu_name'];
            //         $custom_sku_spulist[$spu_name][]= $v;
            //         // $si++;
            //         // $name.=$v;

            //     }

            //     $name = '';
            //     foreach ($custom_sku_spulist as $k => $v) {
            //         # code...
            //         $one_name = $v[0]['spu_name'].$v[0]['num'].$v[0]['color'].$v[0]['size'];
            //         unset($v[0]);
            //         foreach ($v as $sv) {
            //             # code...
            //             $one_name.='+'.$sv['num'].$sv['color'].$sv['size'];
            //         }
            //         $name.=$one_name."+";
            //     }

            //     $name = substr($name, 0, -1);
            //     //库存sku = spu+颜色+尺码

            //     $custom_sku = $spures['spu'].'-XXX-'.$sizeres['identifying'];



            //    //如果有店铺id 则是销售sku
            //    if($shop_id){
            //         $shop_res = $this->GetShop($shop_id);
            //         $shop_id = str_pad($shop_id, 3, 0, STR_PAD_LEFT);
            //         $shop_identifying = $shop_res['identifying'];
            //         if(empty($shop_identifying)){
            //             return ['type'=>'fail','msg'=>'该店铺没有标识，请添加后再尝试生成'];
            //         }
            //         $sku = $shop_identifying.$shop_id.'-'.$custom_sku;
            //         if($special){
            //             $sku = $sku.'-'.$special;
            //         }
            //         $sku_repeat = $this->GetSku($sku);
            //         if($sku_repeat){
            //             $sku_repeat = true;
            //         }else{
            //             $skures['sku'] = $sku;
            //             $skures['custom_sku'] = $custom_sku;
            //             $skures['name'] = $name;
            //             $skures['spu'] = $spures['spu'];
            //             $skures['color'] = 'XXX';
            //             $skures['size'] = $sizeres['identifying'];
            //             Redis::Hset('sku_preview',$sku,json_encode($skures));
            //         }
            //         $skulist[$i]['sku'] =  $sku;
            //         $skulist[$i]['sku_repeat'] =  $sku_repeat;
            //     }else{
            //         //判断是否重复
            //         $cst_repeat =  $this->GetCustomSkus($custom_sku);
            //         if($cst_repeat){
            //             $cst_repeat = true;
            //         }else{
            //             $customskures['custom_sku'] = $custom_sku;
            //             $customskures['name'] = $name;
            //             $customskures['spu'] = $spures['spu'];
            //             $customskures['color'] = 'XXX';
            //             $customskures['size'] = $sizeres['identifying'];
            //             Redis::Hset('custom_sku_preview',$custom_sku,json_encode($customskures));
            //         }
            //         $skulist[$i]['custom_sku'] =  $custom_sku;
            //         $skulist[$i]['cst_repeat'] = $cst_repeat;
            //     }
            //     $skulist[$i]['name'] =  $name;
            //     $i++;
            // }
        }else{
     
                // 获取商铺信息
//                $colorMdl = db::table('self_color_size')
//                    ->get()
//                    ->toArrayList();
                $spuColorMdl = db::table('self_spu_color as a')
                    ->leftJoin('self_color_size as b', 'a.color_id', '=', 'b.id')
                    ->get(['a.base_spu_id', 'a.fabric_color as spu_fabric_color', 'b.fabric_color', 'b.name', 'b.id as color_id', 'b.identifying']);

                $spuColorMdl = json_decode(json_encode($spuColorMdl),true);
                $colorList = [];
                foreach ($spuColorMdl as $sc){
                    $key = $sc['base_spu_id'].'-'.$sc['color_id'];
                    $colorList[$key] = $sc;
                }
//                foreach ($colorMdl as $color){
//                    $colorList[$color['id']] = $color;
//                }
                foreach ($colors as $cv) {
                    # code...
                    //获取颜色信息
//                    $colorres = $this->GetColorSize($cv);
                    $key = $spures['id'] . '-' . $cv;
                    $colorres = $colorList[$key] ?? [];
                    if(!$colorres){
                        return ['type'=>'fail','msg'=>'颜色不存在'];
                    }

                    foreach ($sizes as $sv) {
                        # code...
                        //获取尺寸信息
                        $sizeres = $this->GetColorSize($sv);
                        if(!$sizeres){
                            return ['type'=>'fail','msg'=>'尺码不存在'];
                        }
                        //中文名 = 大类+小类+编号+颜色+尺码
                        $num = str_pad($spures['num'], 5, 0, STR_PAD_LEFT);

                        if(!$spures){
                            return ['type'=>'fail','msg'=>'spu不存在'];
                        }

                        //获取大类
                        $one_cate=  $this->GetCategory($spures['one_cate_id']);

                        //获取小类
                        $three_cate=  $this->GetCategory($spures['three_cate_id']);
                        if(!$one_cate){
                            return ['type'=>'fail','msg'=>'spu大类不存在'];
                        }
                        if(!$three_cate){
                            return ['type'=>'fail','msg'=>'spu小类不存在'];
                        }
                        $marketname = Db::table('self_market')->where('identifying',$spures['market'])->first();
                        if($marketname){
                            $name = $marketname->name.$one_cate['name'].$three_cate['name'].$num.$colorres['name'].$sizeres['name'];
                        }
                        // 新增逻辑 如果是格子色系，取面料色，其余色系取名称
//                        if ($colorres['color_class'] == 'D'){
//                            $colorName = $colorres['fabric_color'];
//                        }else{
//                            $colorName = $colorres['name'];
//                        }
                        // 2023-12-19 新逻辑：优先取 基础spu+颜色的面料色， 其次取颜色的面料色， 最后取颜色名称；
                        if (!is_array($shop_ids)){
                            if (!empty($colorres['spu_fabric_color'])){
                                $colorName = $colorres['spu_fabric_color'];
                            }elseif (!empty($colorres['fabric_color'])){
                                $colorName = $colorres['fabric_color'];
                            }elseif (!empty($colorres['name'])){
                                $colorName = $colorres['name'];
                            }else{
                                $colorName = '';
                            }
                        }else{
                            $colorName = $colorres['name'];
                        }

                        if (empty($colorName)){
                            return ['type'=>'fail','msg'=> $colorres['identifying'].'未维护颜色名称或面料色！'];
                        }
                        $name =$one_cate['name'].$three_cate['name'].$num.$colorName.$sizeres['name'];

                        //库存sku = spu+颜色+尺码
                        $custom_sku = $spures['spu'].'-'.$colorres['identifying'].'-'.$sizeres['identifying'];

                        //判断是否重复
                        $cst_repeat =  $this->GetCustomSkus($custom_sku);
                        if($cst_repeat){
                            $cst_repeat = true;
                        }else{
                            $customskures['custom_sku'] = $custom_sku;
                            $customskures['name'] = $name;
                            $customskures['spu'] = $new_spu;
                            $customskures['color'] = $colorres['identifying'];
                            $customskures['size'] = $sizeres['identifying'];
                            Redis::Hset('datacache:custom_sku_preview',$custom_sku,json_encode($customskures));
                        }

                        if(is_array($shop_ids)){
                             //如果有店铺id 则是销售sku
                            foreach ($shop_ids as $spv) {

                                $shop_res = $this->GetShop($spv);
                                $shop_id = str_pad($spv, 3, 0, STR_PAD_LEFT);
                                $shop_identifying = $shop_res['identifying'];
                                if(empty($shop_identifying)){
                                    return ['type'=>'fail','msg'=>'该店铺没有标识，请添加后再尝试生成'];
                                }
                                $sku = $shop_identifying.$shop_id.'-'.$custom_sku;
                                if($special){
                                    $sku = $sku.'-'.$special;
                                }
                                $sku_repeat = $this->GetSku($sku);
                                if($sku_repeat){
                                    $sku_repeat = true;
                                }else{
                                    $skures['sku'] = $sku;
                                    $skures['custom_sku'] = $custom_sku;
                                    $skures['name'] = $name;
                                    $skures['spu'] = $new_spu;
                                    $skures['color'] = $colorres['identifying'];
                                    $skures['size'] = $sizeres['identifying'];
                                    $skures['shop_id'] = $spv;
                                    Redis::Hset('datacache:sku_preview',$sku,json_encode($skures));
                                }
                                $skulist[$i]['sku'] =  $sku;
                                $skulist[$i]['sku_repeat'] =  $sku_repeat;
                                $skulist[$i]['name'] =  $name;
                                $i++;
                            }

                        }else{                  
                            $skulist[$i]['custom_sku'] =  $custom_sku;
                            $skulist[$i]['cst_repeat'] = $cst_repeat;
                            $skulist[$i]['name'] =  $name;
                            $i++;
                        }
                    }
                }
            

        }
        $res['data'] = $skulist;

        if(!empty($params['shop_id'])){
            //清除缓存
            Redis::Del('datacache:spushop');
        }
        return ['type'=>'success','data'=>$res];

    }



    //生成库存sku
    public function CustomSkuCreate($params){
        $user_id = $params['user_id'];
        $data= $params['custom_sku'];
        $custom_res['create_time'] = time();
        $custom_res['status'] = 1;
        $custom_res['user_id'] = $user_id;
        $operate_user_id = $params['operate_user_id'];
        $custom_res['operate_user_id'] = $operate_user_id;


        foreach ($data as $v) {
            $custom_sku = $v;
            $is_repeat = $this->GetCustomSkus($custom_sku);
            if($is_repeat){
                return ['type'=>'fail','msg'=>'请重新选择，该sku重复'.$custom_sku];
            }
        }
        foreach($data as $v){
            $custom_sku = $v;
            $check = Redis::Hget('datacache:custom_sku_preview',$custom_sku);

            //预览生成
            if($check){
                $custom_res = json_decode($check,true);
                $custom_res['create_time'] = time();
                $custom_res['status'] = 1;
                $custom_res['user_id'] = $user_id;
                $custom_res['type'] = 1;
                $custom_res['operate_user_id'] = $operate_user_id;
            }else{
                //直接生成  spu+颜色+尺码
                $spu = substr($custom_sku, 0, 10);
                $color = substr($custom_sku, 11, 3);
                $size = substr($custom_sku, 15, 5);
                $pattern = "/(.*?)-/s";
                if(preg_match_all($pattern, $size, $matches)){
                    $size = $matches[1][0];
                };
                $spures = Db::table('self_spu')->where('spu',$spu)->orwhere('old_spu',$spu)->first();
                if(!$spures){
                    return ['type'=>'fail','msg'=>'spu:'.$spu.'不存在,或该spu格式异常,请尝试先生成库存sku'];
                }
                $new_spu =  $spures->spu;
                $colorres = Db::table('self_color_size')->where('identifying',$color)->first();
                $sizeres = Db::table('self_color_size')->where('identifying',$size)->first();
                if($spures->type==1){
                    //获取大类
                    $one_cate=  $this->GetCategory($spures->one_cate_id);
                    if(!$one_cate){
                        return ['type'=>'fail','msg'=>'spu大类不存在'];
                    }
                    //获取小类
                    $three_cate=  $this->GetCategory($spures->three_cate_id);
                    if(!$three_cate){
                        return ['type'=>'fail','msg'=>'spu小类不存在'];
                    }

                    //中文名 = 大类+小类+编号+颜色+尺码
                    $num = str_pad($spures->num, 5, 0, STR_PAD_LEFT);
                    $name = $one_cate['name'].$three_cate['name'].$num.$colorres->name.$sizeres->name;

                    $custom_res['custom_sku'] = $custom_sku;
                    $custom_res['spu'] =  $new_spu;
                    $custom_res['color'] = $color;
                    $custom_res['size'] = $size;
                    $custom_res['name'] = $name;
                    $custom_res['type'] = 1;
                }else{
                    //旧组合sku生成，已废弃
                    return ;

                    //中文名
                    //中文名 = 大类+小类+编号+颜色+尺码
                    //第一步，获取该组合spu下的所有sku
                    $custom_sku_res = Db::table('self_group_spu')->where('spu',$spures->spu)->orwhere('spu',$spures->old_spu)->get();

                    $custom_sku_list = array();
                    foreach ($custom_sku_res as $v) {
                        # code...
                        //第二步，获取每个库存sku的spu
                        $customres = $this->GetCustomSkus($v->custom_sku);
                        $color_identifying = $customres['color'];

                        $father_spu =Db::table('self_spu')->where('spu',$customres['spu'])->orwhere('old_spu',$customres['spu'])->first();
                        //获取大类
                        $one_cate=  $this->GetCategory($father_spu->one_cate_id);
                
                        //获取小类
                        $three_cate=  $this->GetCategory($father_spu->three_cate_id);
                        if(!$one_cate){
                            return ['type'=>'fail','msg'=>'spu大类不存在'];
                        }
                        if(!$three_cate){
                            return ['type'=>'fail','msg'=>'spu小类不存在'];
                        }

                        $num = str_pad($father_spu->num, 5, 0, STR_PAD_LEFT);
                        //获取颜色
                        $colors = Db::table('self_color_size')->where('identifying',$customres['color'])->first();
                        $color = $customres['color'];
                        if($colors){
                            $color = $colors->name;
                        }

                        $sun_name = $one_cate['name'].$three_cate['name'].$num.$color.$sizeres->name;
                        $sunnames['spu_name']= $one_cate['name'].$three_cate['name'];
                        $sunnames['num'] = $num;
                        $sunnames['color'] = $color;
                        $sunnames['size'] = $sizeres->name;
                        $sunnames['name'] = $sun_name;
                        //各个颜色只取一个名字
                        $custom_sku_list[$color_identifying] = $sunnames;
                    }
    
    
                    $custom_sku_spulist = array();
                    foreach ($custom_sku_list as $v) {
                        # code...
                        //将所有名字拼接
                        $spu_name = $v['spu_name'];
                        $custom_sku_spulist[$spu_name][]= $v;
                        // $name.=$v;
                        
                    }
    
                    $name = '';

                    foreach ($custom_sku_spulist as $k => $v) {
                        # code...
                        $one_name = $v[0]['spu_name'].$v[0]['num'].$v[0]['color'].$v[0]['size'];
                        unset($v[0]);
                        foreach ($v as $sv) {
                            # code...
                            $one_name.='+'.$sv['num'].$sv['color'].$sv['size'];
                        }
                        $name.=$one_name."+";
                    }

                    $name = substr($name, 0, -1);
    
                    $custom_sku = $spures->spu.'-XXX-'.$sizeres->identifying;
                    $custom_res['custom_sku'] = $custom_sku;
                    $custom_res['spu'] = $spu;
                    $custom_res['color'] = $color;
                    $custom_res['size'] = $size;
                    $custom_res['name'] = $name;
                    $custom_res['type'] = 1;
                    //库存sku = spu+颜色+尺码
                }
            
            }
            $new_spu = Db::table('self_spu')->where('spu', $custom_res['spu'])->orwhere('old_spu',$custom_res['spu'])->first();
            $custom_res['spu'] = $new_spu->spu;
            if(!empty($new_spu->old_spu)){
                $custom_res['spu'] = $new_spu->old_spu;
            }
            $custom_res['spu_id'] = $new_spu->id;
            $custom_res['base_spu_id'] = $new_spu->base_spu_id;
            $colors = Db::table('self_color_size')->where('identifying',$custom_res['color'])->first();
            $custom_res['color_id'] = 0;
            if($colors){
                $custom_res['color_id'] = $colors->id;
                $custom_res['color_name'] = $colors->name;
            }

            $custom_sku_id = Db::table('self_custom_sku')->insertGetId($custom_res);
            if(!$custom_sku_id){
                return ['type'=>'fail','msg'=>'生成失败'];
            }
        }

        return ['type'=>'success','msg'=>'生成成功','data'=>$custom_sku_id];
    }


    //库存sku删除
    public function CustomSkuDel($params){
        //修改状态
        $ids = $params['id'];
        $del['user_id'] = $params['user_id']??'';

        //加入删除日志  type 1 spu 2custom_sku 3sku

        Redis::Del('datacache:self_custom_sku');
        $log['user_id'] =  $del['user_id'];
        $log['type'] = 2;
        if(is_array($ids)){
            foreach ($ids as $id) {
                Redis::Hdel('datacache:custom_sku_id',$id);
                # code...
                $log['id'] =$id;
                $logs = $this->DelLog($log);
                $delresult = Db::table('self_custom_sku')->where('id',$id)->delete();
                Db::table('self_sku')->where('custom_sku_id',$id)->delete();
            }
        }else{
            $log['id'] =$ids;
            Redis::Hdel('datacache:custom_sku_id',$ids);
            $logs = $this->DelLog($log);
            $delresult = Db::table('self_custom_sku')->where('id',$ids)->delete();
        }

        return ['type'=>'success','msg'=>'删除成功'];

    }

    //库存sku列表
    public function CustomSkuList($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $posttype = $params['posttype']??1;

        $where['a.status'] = 1;


        if(isset($params['color'])){
            $where['a.color'] = $params['color'];
        }
        if(isset($params['spu_id'])){
            $where['a.spu_id'] = $params['spu_id'];
        }

        if(isset($params['user_id'])){
            $where['a.user_id'] = $params['user_id'];
        }
        if(isset($params['operate_user_id'])){
            $where['a.operate_user_id'] = $params['operate_user_id'];
        }
        if(isset($params['one_cate_id'])){
            $where['bsp.one_cate_id'] = $params['one_cate_id'];
        }
        if(isset($params['two_cate_id'])){
            $where['bsp.two_cate_id'] = $params['two_cate_id'];
        }
        if(isset($params['three_cate_id'])){
            $where['bsp.three_cate_id'] = $params['three_cate_id'];
        }
        if(isset($params['platform_id'])){
            $where['b.platform_id'] = $params['platform_id'];
        }

        $list = Db::table('self_custom_sku as a')
            ->leftjoin('self_spu as b','b.id', '=', 'a.spu_id')
            ->leftJoin('self_cus_info as c','c.custom_sku_id','=','a.id');

        if(isset($params['start_time'])&&isset($params['end_time'])){
            $start_time = strtotime($params['start_time']);
            $end_time = strtotime($params['end_time']); 
            $list = $list->whereBetween('a.create_time', [$start_time, $end_time]);
        }

        if(isset($params['custom_sku'])){
            $list = $list->where(function($query) use($params){
                $query->where('a.custom_sku','like','%'.$params['custom_sku'].'%')->orwhere('a.old_custom_sku','like','%'.$params['custom_sku'].'%');
            });
        }
        if(isset($params['spu'])){
            $list = $list->where(function($query) use($params){
                $query->where('b.spu','like','%'.$params['spu'].'%')->orwhere('b.old_spu','like','%'.$params['spu'].'%');
            });

        }
        if (!isset($params['user_id']) || empty($params['user_id'])){
            if (isset($params['token']) && !empty($params['token'])){
                $users = db::table('users')->where('token',$params['token'])->first();
                $params['user_id'] = $users->Id ?? 0;
            }else{
                $params['user_id'] = 0;
            }
        }
        if(isset($params['is_weight'])){
            if($params['is_weight']==1){
                $list = $list->where('c.product_weight','>',0);
            }else{
                $list = $list->where('c.product_weight','=',0);
            }
        }
        $controller = new Controller();
        $power = $controller->powers(['user_id' => $params['user_id'], 'identity' => ['product_contract_price']]);

        $list =  $list->where($where);
        $totalNum = $list->count();
        if($posttype==1){
            $list =  $list->offset($page)
                ->limit($limit);
        }
        $list =  $list->leftjoin('self_color_size as cz','a.size','=','cz.identifying')
                ->select('a.operate_user_id','a.length','a.height','a.width','a.weight','a.name','a.custom_sku','b.spu','b.old_spu','a.id','a.user_id','a.old_custom_sku','a.create_time',
                    'b.platform_id','b.one_cate_id','b.two_cate_id','b.three_cate_id','a.type','c.product_weight','a.box_num')
                ->orderBy('a.create_time','desc')
                ->orderBy('a.spu','asc')
                ->orderby('a.color','ASC')
                ->orderby('cz.sort','ASC')
                // ->orderBy('a.spu','asc')
                // ->orderby('a.color','ASC')
                ->get();


        foreach ($list as $v) {
            if($v->old_spu){
                $v->spu =$v->old_spu;
            }
            if($v->product_weight==null){
                $v->product_weight = 0;
            }
            //运营负责人
            $v->operate_user = '';
            $operate_users = $this->GetUsers($v->operate_user_id);
            if($operate_users){
                $v->operate_user = $operate_users['account'];
            }  

            $v->sku_count = Db::table('self_sku')->where('custom_sku_id',$v->id)->count();
            //用户名
            $v->account = '';
            $users = $this->GetUsers($v->user_id);
            if($users){
                $v->account = $users['account'];
            }

            //大类
            $v->one_cate = '';
            $one_cate = $this->GetCategory($v->one_cate_id);
            if($one_cate){
                $v->one_cate = $one_cate['name'];
            }

            //二类
            $v->two_cate = '';
            $two_cate = $this->GetCategory($v->two_cate_id);
            if($two_cate){
                $v->two_cate = $two_cate['name'];
            }

            //三类
            $v->three_cate = '';
            $three_cate = $this->GetCategory($v->three_cate_id);
            if($three_cate){
                $v->three_cate = $three_cate['name'];
            }

            //平台
            $v->platform = '';
            $platform = $this->GetPlatform($v->platform_id);
            if($platform){
                $v->platform = $platform['name'];
            }

            $v->img = $this->GetCustomskuImg($v->custom_sku);//图片


            $v->create_time = date('Y-m-d H:i:s',$v->create_time);

        }
            
        // if($posttype==2){
        //     $this->ExcelCustomSku($list);
        // }

    
        if($posttype==2){
                  
            $p['title']='库存sku表'.time();

            $listtlt = [
                'name'=>'中文名',
                'custom_sku'=>'库存sku',
                'img'=>'图片',
                'old_custom_sku'=>'旧库存sku',
                'spu'=>'spu',
                'sku_count'=>'销售sku数量',
                'platform'=>'平台',
                'one_cate'=>'大类',
                'two_cate'=>'二类',
                'three_cate'=>'三类',
                'product_weight'=>'重量（kg）',
                'operate_user'=>'运营人员',
            ];

    
            $p['title_list']  = $listtlt;
            $p['data'] =   $list;
            $p['user_id'] = Db::table('users')->where('token',$params['token'])->first()->Id;   
            $p['type'] = '库存sku表-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
            // $this->ExcelSku($list);
        }
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];

    }


    //库存sku绑定
    public function SpuOldBind($params){
        $type = $params['type'];
        $id = $params['id'];
        $old= $params['old']??'';
        switch ($type) {
            case 'spu':
                # code...
                if (!empty($old)){
                    // 查询old_spu是否唯一
                    $spuModel = new SpuModel();
                    $check = $spuModel::query()->where('old_spu', $old)->first();
                    if (!empty($check)){
                        return ['type'=>'fail','msg'=>"绑定失败！旧SPU：".$old."已存在！"];
                    }
                }
                $spu = Db::table('self_spu')->where('id',$id)->first()->spu;
                Redis::Hdel('datacache:newoldspu',$spu);
                Redis::Hdel('datacache:self_spu',$spu);

                $change['old_spu'] = $old;
                $updateresult = Db::table('self_spu')->where('id',$id)->update($change);
                break;
            case 'base_spu':
                if (!empty($old)){
                    // 查询old_spu是否唯一
                    $spuModel = new SpuModel();
                    $check = $spuModel::query()->where('old_spu', $old)->first();
                    if (!empty($check)){
                        return ['type'=>'fail','msg'=>"绑定失败！旧SPU：".$old."已存在！"];
                    }
                }
                $spu = Db::table('self_spu')->where('id',$id)->first()->spu;
                Redis::Hdel('datacache:newoldspu',$spu);
                Redis::Hdel('datacache:self_spu',$spu);

                $change['old_spu'] = $old;
                $updateresult = Db::table('self_spu')->where('id',$id)->update($change);
                break;
                // # code...
                // $spu = Db::table('self_base_spu')->where('id',$id)->first()->base_spu;
                // $change['old_base_spu'] = $old;
                // $updateresult = Db::table('self_base_spu')->where('id',$id)->update($change);
                // break;
            case 'custom_sku':
                # code...
                if (!empty($old)){
                    // 查询old_custom_sku是否唯一
                    $customSkuModel = new CustomSkuModel();
                    $check = $customSkuModel::query()->where('old_custom_sku', $old)->first();
                    if (!empty($check)){
                        return ['type'=>'fail','msg'=>"绑定失败！旧库存SKU：".$old."已存在！"];
                    }
                }
                Redis::Hdel('datacache:self_custom_sku',$old);
                $cus = Db::table('self_custom_sku')->where('id',$id)->first();

                $change['old_custom_sku'] = $old;
                $updateresult = Db::table('self_custom_sku')->where('id',$id)->update($change);
                db::table('purchase_order_list')->where('sku',$old)->update(['custom_sku_id'=>$cus->id,'spu_id'=>$cus->spu_id]);
                break;
            case 'sku':
                # code...
                $change['old_sku'] = $old;
                if (!empty($old)) {
                    // 查询old_sku是否唯一
                    $skuModel = new SkuModel();
                    $check = $skuModel::query()->where('old_sku', $old)->first();
                    if (!empty($check)) {
                        return ['type' => 'fail', 'msg' => "绑定失败！旧渠道SKU：" . $old . "已存在！"];
                    }
                }
                //销售状态
                if(isset($params['sales_status'])){
                    $change['sales_status'] = $params['sales_status'];
                }

                //款式
                if(isset($params['goods_style'])){
                    $change['goods_style'] = $params['goods_style'];
                }

                $updateresult = Db::table('self_sku')->where('id',$id)->update($change);
                break;

            default:
                # code...
                return ['type'=>'fail','msg'=>'类型错误'];
                break;
        }
        if($updateresult){
            return ['type'=>'success','msg'=>'绑定成功'];
        }
    }


    //库存sku绑定
    public function SkuUpdate($params){
        $id = $params['id'];

        $add['old_sku'] = $params['old_sku'];

        //销售状态
        $add['sales_status'] = $params['sales_status'];

        //款式
        $add['goods_style'] = $params['goods_style'];


        $updateresult = Db::table('self_sku')->where('id',$id)->update($add);

        if($updateresult){
            return ['type'=>'success','msg'=>'绑定成功'];
        }
    }

    //生成销售sku
    public function SkuCreateb($params){
        $user_id = $params['user_id'];
        $shop_id =  $params['shop_id'];
        $operate_user_id = $params['operate_user_id'];
        $data= $params['sku'];
        $sku_res['create_time'] = time();
        $sku_res['status'] = 1;
        $sku_res['user_id'] = $user_id;
        $sku_res['shop_id'] = $shop_id;
        $sku_res['operate_user_id'] = $operate_user_id;

        foreach ($data as $v) {
            $sku = $v;
            $sku_repeat = $this->GetSku($sku);
            if($sku_repeat){
                return ['type'=>'fail','msg'=>'请重新选择，该sku重复'.$sku];
            }
        }
        foreach($data as $v){
            $sku = $v;
            // $custom_sku = substr($sku, 6, 25);
            $check = Redis::Hget('datacache:sku_preview',$sku);
            if(!$check){
                return ['type'=>'fail','msg'=>'非法生成，请先预览生成'];
            }
            $skures = json_decode($check,true);
            $custom_sku = $skures['custom_sku'];
            // //是否存在库存sku
            // $is_repeat = $this->GetCustomSku($custom_sku);
            // if(!$is_repeat){
            //     $cusres['user_id'] = $user_id;
            //     $cusres['operate_user_id'] = $operate_user_id;
            //     $cusres['custom_sku']['0'] = $custom_sku;
            //     $custom = $this->CustomSkuCreate($cusres);
            //     if ($custom['type'] != 'success') {
            //         return ['type'=>'fail','msg'=>'库存sku生成失败'.$custom_sku];
            //     }
            // }

            //预览生成


            $sku_res['custom_sku'] = $custom_sku;
            $sku_res['custom_sku_id'] = $this->GetCustomSkuId($custom_sku);
            $sku_res['spu_id'] =   $this->GetSpuId($skures['spu']);
            $sku_res['spu'] = $skures['spu'];
            $sku_res['sku'] = $skures['sku'];


            $res = Db::table('self_sku')->insert($sku_res);
            if(!$res){
                return ['type'=>'fail','msg'=>'生成失败'];
            }
        }

        return ['type'=>'success','msg'=>'生成成功'];
    }
    //生成销售sku
    public function SkuCreate($params){
        $user_id = $params['user_id'];
        $shop_id =  $params['shop_id'];
        $operate_user_id = $params['operate_user_id'];
        $data= $params['sku'];
        $sku_res['create_time'] = time();
        $sku_res['status'] = 1;
        $sku_res['user_id'] = $operate_user_id;
//        $sku_res['shop_id'] = $shop_id;
        $sku_res['operate_user_id'] = $user_id;

        foreach ($data as $v) {
            $sku = $v;
            $sku_repeat = $this->GetSku($sku);
            if($sku_repeat){
                return ['type'=>'fail','msg'=>'请重新选择，该sku重复'.$sku];
            }
        }

        foreach($data as $v){
            $sku = $v;
            // $custom_sku = substr($sku, 6, 25);
            $check = Redis::Hget('datacache:sku_preview',$sku);
            if(!$check){
                return ['type'=>'fail','msg'=>'非法生成，请先预览生成'];
            }
            $skures = json_decode($check,true);
            $custom_sku = $skures['custom_sku'];
            //是否存在库存sku
            $is_repeat = $this->GetCustomSkus($custom_sku);
            if(!$is_repeat){
                // var_dump($custom_sku);
                // var_dump(strlen($custom_sku));
                // if(strlen($custom_sku)!=17){
                //     return ['type'=>'fail','msg'=>'该spu为特殊spu，请生成对应库存sku后再生成销售sku'];
                // }
                $cusres['user_id'] = $user_id;
                $cusres['operate_user_id'] = $operate_user_id;
                $cusres['custom_sku']['0'] = $custom_sku;
                $custom = $this->CustomSkuCreate($cusres);
                // try {
                //     //code...
                //     $custom = $this->CustomSkuCreate($cusres);
                // } catch (\Throwable $th) {
                //     //throw $th;

                //     return ['type'=>'fail','msg'=>'该spu为特殊spu，请生成对应库存sku:【'.$custom_sku.'】后再生成销售sku'];
                // }
               
                if ($custom['type'] != 'success') {
                    return ['type'=>'fail','msg'=>'库存sku生成失败'.$custom_sku.$custom['msg']];
                }else{
                    $custom_sku_id = $custom['data'];
                }
            }

            // //预览生成
            // foreach ($shop_id as $s){
            //     if(strpos($sku,$s)){
            //         $sku_res['shop_id'] = $s;
            //     }
            // }

            $sku_res['shop_id'] = $skures['shop_id'];
            $sku_res['custom_sku'] = $custom_sku;
            $sku_res['spu'] = $skures['spu'];
            $sku_res['sku'] = $skures['sku'];

            $sku_res['custom_sku_id'] = $this->GetCustomSkuId( $custom_sku);
            $sku_res['spu_id'] = $this->GetSpuId($skures['spu']);

            $sku_id = Db::table('self_sku')->insertGetId($sku_res);
            //加入补货预警队列
            Redis::Lpush('datacache:go-buhuo-one-list',$sku_id);
            if(!$sku_id){
                return ['type'=>'fail','msg'=>'生成失败'];
            }
        }

        return ['type'=>'success','msg'=>'生成成功'];
    }
    //销售sku删除
    public function SkuDel($params){
        //修改状态
        $ids = $params['id'];
        $del['user_id'] = $params['user_id']??'';
        $log['user_id'] =  $del['user_id'];
        $log['type'] = 3;
        Redis::Del('self_sku');
        if(is_array($ids)){  
            foreach ($ids as $id) {
                # code...
                $log['id'] =$id;
                $logs = $this->DelLog($log);
                $delresult = Db::table('self_sku')->where('id',$id)->delete();

            }
        }else{
            $log['id'] =$ids;
            $logs = $this->DelLog($log);
            $delresult = Db::table('self_sku')->where('id',$ids)->delete();
        }  
        //加入删除日志  type 1 spu 2custom_sku 3sku
        return ['type'=>'success','msg'=>'删除成功'];

    }

    //销售sku上下架
    public function Sku_update($params){
        //修改状态
        $ids = $params['id'];
        $status = $params['status'];
//        $del['user_id'] = $params['user_id']??'';
//        $log['user_id'] =  $del['user_id'];
//        $log['type'] = 3;

        if(is_array($ids)){
            foreach ($ids as $id) {
                # code...
//                $log['id'] =$id;
//                $logs = $this->DelLog($log);
                $delresult = Db::table('self_sku')->where('id',$ids)->update(['status'=>$status]);
            }
        }else{
//            $log['id'] =$ids;
//            $logs = $this->DelLog($log);
            $delresult = Db::table('self_sku')->where('id',$ids)->update(['status'=>$status]);
        }
        if($status==1){
            return ['type'=>'success','msg'=>'上架成功'];
        }else{
            return ['type'=>'success','msg'=>'下架成功'];
        }


    }

    //销售sku列表
    public function SkuList($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $posttype = $params['posttype']??1;

        $where = array();
        if(isset($params['color'])){
            $where['sc.color'] = $params['color'];
        }
        if(isset($params['user_id'])){
            $where['a.user_id'] = $params['user_id'];
        }
        if(isset($params['user_id'])){
            $where['a.user_id'] = $params['user_id'];
        }
        if(isset($params['operate_user'])){
            $where['a.operate_user'] = $params['operate_user'];
        }
        if(isset($params['one_cate_id'])){
            $where['bsp.one_cate_id'] = $params['one_cate_id'];
        }
        if(isset($params['two_cate_id'])){
            $where['bsp.two_cate_id'] = $params['two_cate_id'];
        }
        if(isset($params['three_cate_id'])){
            $where['bsp.three_cate_id'] = $params['three_cate_id'];
        }
        if(isset($params['platform_id'])){
            $where['spp.platform_id'] = $params['platform_id'];
        }

        if(isset($params['shop_id'])){
            $where['a.shop_id'] = $params['shop_id'];
        }


        if(isset($params['spu_id'])){
            $where['a.spu_id'] = $params['spu_id'];
        }


        if(isset($params['fasin'])){
            $where['a.fasin'] = $params['fasin'];
        }


        if(isset($params['custom_sku_id'])){
            $where['a.custom_sku_id'] = $params['custom_sku_id'];
        }

            // DB::connection()->enableQueryLog(); 
        $list = Db::table('self_sku as a')->where($where)->leftjoin('shop as spp','a.shop_id', '=', 'spp.Id')->leftjoin('self_custom_sku as sc','a.custom_sku_id', '=', 'sc.id')->leftjoin('self_spu as sp','sc.spu_id', '=', 'sp.id')->leftjoin('self_base_spu as bsp','bsp.id','=','sp.base_spu_id');
        $listcount = Db::table('self_sku as a')->where($where)->leftjoin('self_custom_sku as sc','a.custom_sku_id', '=', 'sc.id')->leftjoin('shop as spp','a.shop_id', '=', 'spp.Id')->leftjoin('self_spu as sp','sc.spu_id', '=', 'sp.id')->leftjoin('self_base_spu as bsp','bsp.id','=','sp.base_spu_id');
        if(isset($params['start_time'])&&isset($params['end_time'])){
            $start_time = strtotime($params['start_time']);
            $end_time = strtotime($params['end_time']); 
            $list = $list->whereBetween('a.create_time', [$start_time, $end_time]);
            $listcount = $listcount->whereBetween('a.create_time', [$start_time, $end_time]);
        }

        if(isset($params['custom_sku'])){

            
            $list = $list->where(function($query) use($params){
                $query->where('sc.custom_sku','like','%'.$params['custom_sku'].'%')->orwhere('sc.old_custom_sku','like','%'.$params['custom_sku'].'%');
            });
            $listcount = $listcount->where(function($query) use($params){
                $query->where('sc.custom_sku','like','%'.$params['custom_sku'].'%')->orwhere('sc.old_custom_sku','like','%'.$params['custom_sku'].'%');
            });
        }



        if(isset($params['spu'])){
            $list = $list->where(function($query) use($params){
                $query ->where('sp.spu','like','%'.$params['spu'].'%')->orwhere('sp.old_spu','like','%'.$params['spu'].'%');
            });
           

            $listcount = $listcount->where(function($query) use($params){
                $query ->where('sp.spu','like','%'.$params['spu'].'%')->orwhere('sp.old_spu','like','%'.$params['spu'].'%');
            });
        }
        if(isset($params['sku'])){
            $listcount = $listcount->where(function($query) use($params){
                $query->where('a.sku','like','%'.$params['sku'].'%')->orwhere('a.old_sku','like','%'.$params['sku'].'%');
            });
            $list = $list->where(function($query) use($params){
                $query->where('a.sku','like','%'.$params['sku'].'%')->orwhere('a.old_sku','like','%'.$params['sku'].'%');
            });
        }

        if (isset($params['limit']) && !isset($params['posttype'])){
            $list = $list->offset($page)
            ->limit($limit);
        }

      

  
        $list = $list->leftjoin('self_color_size as cz','sc.size','=','cz.identifying')
        ->select('a.fasin','a.operate_user_id','a.sku','a.old_sku','sp.spu','sp.old_spu','sc.custom_sku','sc.old_custom_sku','spp.platform_id','a.shop_id','sc.name','a.id','a.user_id','a.create_time','a.goods_style','a.plan_multiple','a.sales_status','a.status','sp.platform_id','sp.one_cate_id','sp.two_cate_id','sp.three_cate_id','sp.market')
        // ->orderBy('a.create_time','desc')
        ->orderby('a.create_time','DESC')
        ->orderBy('a.spu','asc')
        ->orderby('a.shop_id','ASC')
        ->orderby('sc.color','ASC')
        ->orderby('cz.sort','ASC')
//        ->offset($page)
//        ->limit($limit)
        ->get();

        // print_r(DB::getQueryLog());
        $totalNum =  $listcount->count();


        // $listarr = json_decode(json_encode($list),true);
        // $sku = array_column($listarr,'sku');
        // $old_sku = array_column($listarr,'old_sku');
        // $skulist = array_merge($sku,$old_sku);
        // $product_detail = DB::table('product_detail')->whereIn('sellersku',$skulist)->select('sellersku','parent_asin','fnsku','asin')->get();
        // $product_detail = json_decode(json_encode($product_detail),true);
        // $sku_product_arr = [];
        // if(!empty($product_detail)){
        //     //拼接亚马逊产品信息
        //     foreach ($product_detail as $p){
        //         $sku_product_arr[$p['sellersku']]=$p;
        //     }
        // }
        // print_r(DB::getQueryLog());
        $totalNum =  $listcount->count();


        foreach ($list as $v) {

            if($posttype==1){
                //匹配亚马逊产品信息
                $v->fnsku = '';
                $v->father_asin = '';
                $v->asin = '';

                $product = DB::table('product_detail')->where('sellersku',$v->sku)->select('sellersku','parent_asin','fnsku','asin')->first();
                if(!$product){
                    $product = DB::table('product_detail')->where('sellersku',$v->old_sku)->select('sellersku','parent_asin','fnsku','asin')->first();
                }

                if($product){
                    $v->fnsku = $product->fnsku??'';
                    $v->asin = $product->asin??'';
                }

                $v->father_asin = $v->fasin??'';
            }

            // if(isset($sku_product_arr[$v->sku])){
            //     $v->fnsku = $sku_product_arr[$v->sku]['fnsku'];
            //     $v->father_asin = $sku_product_arr[$v->sku]['parent_asin'];
            //     $v->asin = $sku_product_arr[$v->sku]['asin'];
            // }elseif(isset($sku_product_arr[$v->old_sku])){
            //     $v->fnsku = $sku_product_arr[$v->old_sku]['fnsku'];
            //     $v->father_asin = $sku_product_arr[$v->old_sku]['parent_asin'];
            //     $v->asin = $sku_product_arr[$v->old_sku]['asin'];
            // };
            //运营负责人
            $v->operate_user = '';
            $operate_users = $this->GetUsers($v->operate_user_id);
            if($operate_users){
                $v->operate_user = $operate_users['account'];
            }  
            if($v->old_spu){
                $v->spu = $v->old_spu;
            }

            if($v->old_custom_sku){
                $v->custom_sku = $v->old_custom_sku;
            }
            // $v->sku = $v->old_sku??$v->sku;
            //负责人
            $v->user = '';
            $users = $this->GetUsers($v->user_id);
            if($users){
                $v->user = $users['account'];
            }  

            //用户名
            $v->account = '';
            $users = $this->GetUsers($v->user_id);
            if($users){
                $v->account = $users['account'];
            }

            //大类
            $v->one_cate = '';
            $one_cate = $this->GetCategory($v->one_cate_id);
            if($one_cate){
                $v->one_cate = $one_cate['name'];
            }

            //二类
            $v->two_cate = '';
            $two_cate = $this->GetCategory($v->two_cate_id);
            if($two_cate){
                $v->two_cate = $two_cate['name'];
            }

            //三类
            $v->three_cate = '';
            $three_cate = $this->GetCategory($v->three_cate_id);
            if($three_cate){
                $v->three_cate = $three_cate['name'];
            }

    
            //店铺
            $v->shop_name = '';

            //平台
            $v->platform = '';
            $shop = $this->GetShop($v->shop_id);
            if($shop){
                $v->shop_name = $shop['shop_name'];
                $platform = $this->GetPlatform($shop['platform_id']);
                if($platform){
                    $v->platform = $platform['name'];
                }
            }

           
            $v->create_time = date('Y-m-d H:i:s',$v->create_time);


            $v->img = $this->GetCustomskuImg($v->custom_sku);//图片
        }

  
            
        if($posttype==2){
                  
            $p['title']='渠道sku表'.time();

            $listtlt = [
                'name'=>'中文名',
                'custom_sku'=>'库存sku',
                'sku'=>'销售sku',
                'old_sku'=>'旧销售sku',
                'spu'=>'spu',
                'fasin'=>'父asin',
                'platform'=>'平台',
                'market'=>'国家标识',
                'shop_name'=>'店铺',
                'one_cate'=>'大类',
                'two_cate'=>'二类',
                'three_cate'=>'三类',
                'user'=>'运营人员',
            ];

    
            $p['title_list']  = $listtlt;
            $p['data'] =   $list;
            $p['user_id'] = Db::table('users')->where('token',$params['token'])->first()->Id;
            $p['type'] = '渠道sku表-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
            // $this->ExcelSku($list);
        }
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];

    }


    //spu颜色添加
    public function SelfSpuColorAdd($params){
        try {
            if (isset($params['order_start_quantity']) && $params['order_start_quantity'] < 0){
                throw new \Exception('起订量不正确！');
            }
            $insert['base_spu_id'] = $params['id'];
            $insert['status'] = 1;
            $insert['img'] = $params['img']??'';
            $insert['user_id'] = $params['user_id'];
            $insert['color_id'] = $params['color_id'];
            $insert['addtime'] = date('Y-m-d H:i:s');
            $insert['order_start_quantity'] = $params['order_start_quantity'] ?? 0;
            $insert['fabric_color'] = $params['fabric_color']??'';
            $res = Db::table('self_spu_color')->where($insert)->first();
            if($res){
                return ['type'=>'fail','msg'=>'该颜色已存在'];
            }else{
                Db::table('self_spu_color')->insert($insert);
            }

            return ['type'=>'success','msg'=>'添加成功'];
        }catch (\Exception $e){
            return ['type'=>'fail','msg'=>'添加失败！原因：'.$e->getMessage()];
        }
    }


    //spu尺码添加
    public function SpuSizeAdd($params){
        $insert['base_spu_id'] = $params['base_spu_id'];
        $insert['user_id'] = $params['user_id'];
        $size_ids = $params['size_ids'];

        if(!is_array($size_ids)){
            return ['type'=>'fail','msg'=>'参数格式错误'];
        }
        foreach ($size_ids as $size_id) {
            # code...
            $insert['size_id'] = $size_id;
            $res = Db::table('self_spu_size')->where($insert)->first();
            if($res){
                return ['type'=>'fail','msg'=>'该尺码已存在'];
            }else{
                Db::table('self_spu_size')->insert($insert);
            }
        }
       

        return ['type'=>'success','msg'=>'添加成功'];

    }

    //spu尺码删除
    public function SpuSizeDel($params){
        $id = $params['id'];
        Db::table('self_spu_size')->where('id',$id)->delete();
        return ['type'=>'success','msg'=>'删除成功'];
    }

    public function SpuSize($params){
        $id = $params['base_spu_id'];
        $list = Db::table('self_spu_size')->where('base_spu_id',$id)->get();
        foreach ($list as $v) {
            # code...
            $sizes = $this->GetColorSize($v->size_id);
            $v->size_identifying  =  $sizes['identifying'];
            $v->size_name = $sizes['name'];
        }
        return ['type'=>'success','msg'=>'获取成功','data'=>$list];
    }

    //spu颜色修改
    public function SelfSpuColorEdit($params){
        try {
            $this->_checkSelfSpuColorEditParams($params);
            $id = $params['id'];
            $update['status'] = 1;
            $update['color_id'] = $params['color_id'];
            $update['img'] = $params['img'];
            $update['order_start_quantity'] = $params['order_start_quantity'] ?? 0;
            $update['fabric_color'] = $params['fabric_color']??'';
            Db::table('self_spu_color')->where('id',$id)->update($update);

            // $spu =  Db::table('self_spu_color')->where('id',$id)->first();
            // // redis::Hdel('base_spu_img', $base_spu->base_spu);
            // $spus = Db::table('self_spu')->where('base_spu_id',$spu->base_spu_id)->get();
            // foreach ($spus as $spu) {
            //     # code...
            //     redis::Hdel('spu_img', $spu->spu);
            //     if(isset($spu->old_spu)){
            //         redis::Hdel('spu_img', $spu->old_spu);
            //     }
            // }


            // $res = Db::table('self_spu_color')->where($update)->first();
            // if($res){
            //     return ['type'=>'fail','msg'=>'该颜色已存在'];
            // }else{
            //     Db::table('self_spu_color')->where('id',$id)->update($update);
            // }

            return ['type'=>'success','msg'=>'修改成功'];
        }catch (\Exception $e){
            return ['type'=>'error','msg'=>'修改失败!原因：'.$e->getMessage()];
        }
    }

    //spu颜色删除
    public function SelfSpuColorDel($params){
        $id = $params['id'];
        $spu =  Db::table('self_spu_color')->where('id',$id)->first();
        $base_spu = Db::table('self_base_spu')->where('id',$spu->base_spu_id)->first();
        redis::Hdel('base_spu_img', $base_spu->base_spu);
        $spus = Db::table('self_spu')->where('base_spu_id',$spu->base_spu_id)->get();
        foreach ($spus as $spu) {
            # code...
            redis::Hdel('spu_img', $spu->spu);
            if(isset($spu->old_spu)){
                redis::Hdel('spu_img', $spu->old_spu);
            }
        }
        Db::table('self_spu_color')->where('id',$id)->delete();
        return ['type'=>'success','msg'=>'删除成功'];
    }



    //spu下单颜色禁用
    public function SelfSpuColorPlaceOrderAdd($params){
        $insert['spu_id'] = $params['id'];
        $insert['user_id'] = $params['user_id'];
        $insert['color_id'] = $params['color_id'];
        $res = Db::table('self_spu_color_isplace')->where($insert)->first();
        if($res){
            return ['type'=>'fail','msg'=>'该颜色已存在'];
        }else{
            Db::table('self_spu_color_isplace')->insert($insert);
        }

        return ['type'=>'success','msg'=>'添加成功'];

    }

     //spu下单颜色启用
     public function SelfSpuColorPlaceOrderDel($params){
        $spu_id = $params['id']??0;
        $color_id = $params['color_id']??0;
        if($spu_id<=0||$color_id<=0){
            return ['type'=>'fail','msg'=>'spuid.colorid必传'];
        }
        Db::table('self_spu_color_isplace')->where('spu_id',$spu_id)->where('color_id',$color_id)->delete();
        return ['type'=>'success','msg'=>'删除成功'];
    }

    

    public function updatetest($params){
        // $new_spu = $params['new_spu'];
        $pagenum = $params['page'];

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * 5000;
        }

        // $table = $params['table'];
        // $type = $params['type']??1;
        // $list =  Db::select('select * from amazon_place_order_detail');

        $list = Db::table('amazon_place_order_detail')->groupby('order_id')->offset($page)->limit(5000)->get();
        $rt = [];
       foreach ($list as $v) {
            $rt[$v->order_id] = Db::select('select custom_sku ,count(1)as counts from amazon_place_order_detail where order_id = 10028 GROUP BY custom_sku having counts>1');
       }

       return $rt;
    }

    //excel导出 -spu
    public function ExcelSpu($params){
        $data = json_decode(json_encode($params), true);
        $obj = new \PHPExcel();


        $fileName = "spu列表" . date('Y-m-d');
        $fileType = 'xlsx';

        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('spu列表'); //设置标题

        // 设置当前sheet
        $obj->setActiveSheetIndex(0);

        @ob_end_clean();
        // 设置当前sheet的名称
        $obj->getActiveSheet()->setTitle('spu列表');

        // 列标
        $list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L'];

        // 填充第一行数据
        $obj->getActiveSheet()
            ->setCellValue($list[0] . '3', 'spu')
            ->setCellValue($list[1] . '3', 'old_spu')
            ->setCellValue($list[2] . '3', '类型')
            ->setCellValue($list[3] . '3', '库存sku数量')
            ->setCellValue($list[4] . '3', '销售sku数量')
            ->setCellValue($list[5] . '3', '平台')
            ->setCellValue($list[6] . '3', '大类')
            ->setCellValue($list[7] . '3', '二类')
            ->setCellValue($list[8] . '3', '三类')
            ->setCellValue($list[9] . '3', '产品负责人')
            ->setCellValue($list[10] . '3', '供应链负责人')
            ->setCellValue($list[11] . '3', '创建者');



        // 填充第n(n>=2, n∈N*)行数据
        $length = count($data);
        for ($i = 0; $i < $length; $i++) {
            $obj->getActiveSheet()->setCellValue($list[0] . ($i + 4), $data[$i]['spu'], \PHPExcel_Cell_DataType::TYPE_STRING);//将其设置为文本格式
            $obj->getActiveSheet()->setCellValue($list[1] . ($i + 4), $data[$i]['old_spu'], \PHPExcel_Cell_DataType::TYPE_STRING);//将其设置为文本格式
            if($data[$i]['type']==1){
                $type = '正常spu';
            }else{
                $type = '组合spu';
            }
            $obj->getActiveSheet()->setCellValue($list[2] . ($i + 4), $type, \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[3] . ($i + 4), $data[$i]['custom_sku_count'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[4] . ($i + 4), $data[$i]['sku_count'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[5] . ($i + 4), $data[$i]['platform'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[6] . ($i + 4), $data[$i]['one_cate'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[7] . ($i + 4), $data[$i]['two_cate'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[8] . ($i + 4), $data[$i]['three_cate'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[9] . ($i + 4), $data[$i]['operate_user'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[10] . ($i + 4), $data[$i]['supply_user'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[11] . ($i + 4), $data[$i]['user'], \PHPExcel_Cell_DataType::TYPE_STRING);
        }

        // 设置加粗和左对齐
        foreach ($list as $col) {
            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($col . '1')->getFont()->setBold(true);
            // 设置第1-n行，左对齐
            for ($i = 1; $i <= $length + 1; $i++) {
                $obj->getActiveSheet()->getStyle($col . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            }
        }

        // 设置列宽
        $obj->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('B')->setWidth(30);
        $obj->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('J')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('K')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('L')->setWidth(20);

        // 导出
        @ob_clean();
        $path = '/var/www/online/zity/public/admin/export/testspulist.xlsx';
        if ($fileType == 'xls') {
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xls');
            header('Cache-Control: max-age=1');
            $objWriter = new \PHPExcel_Writer_Excel5($obj);
            
            $objWriter->save($path);
            exit;
        } elseif ($fileType == 'xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');
            header('Cache-Control: max-age=1');
            $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
            $objWriter->save($path);
            exit;
        }
    }


    //获取sku供应商列表
    public function GetCusSuppliersM($params){
        $custom_sku = $params['custom_sku'];
        $custom_sku_id = $this->GetCustomSkuId($custom_sku);
        $list = db::table('self_cus_info_attr as a')->leftjoin('suppliers as b','a.suppliers_id','=','b.Id')->leftjoin('self_custom_sku as c','a.custom_sku_id','=','c.id')->where('a.status',1)->where('a.custom_sku_id',$custom_sku_id)->select('a.suppliers_id','a.price','b.name','c.base_spu_id')->get();
        if(!$list){
            $cusres = db::table('self_custom_sku')->where('id',$custom_sku_id)->first();
            $list = db::table('self_spu_info_attr as a')->leftjoin('suppliers as b','a.suppliers_id','=','b.Id')->where('a.status',1)->where('a.base_spu_id', $cusres->base_spu_id)->select('a.suppliers_id','a.price','b.name','a.base_spu_id')->get();
        }
        foreach ($list as $v) {
            # code...
            $suppliers_price = 0;
            $spus =  db::table('self_spu_info')->where('base_spu_id',$v->base_spu_id)->select('unit_price')->first();
            if($spus){
                $suppliers_price = $spus->unit_price;
            }
            $v->suppliers_price = $suppliers_price;
           
        }
        return ['type'=>'success','data' => $list];
    }
        
    //excel导出 -库存sku
    public function ExcelCustomSku($params){
        $data = json_decode(json_encode($params), true);
        $obj = new \PHPExcel();


        $fileName = "库存sku" . date('Y-m-d');
        $fileType = 'xlsx';

        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('库存sku'); //设置标题

        // 设置当前sheet
        $obj->setActiveSheetIndex(0);

        // 设置当前sheet的名称
        $obj->getActiveSheet()->setTitle('库存sku');

        // 列标
        $list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];

        // 填充第一行数据
        $obj->getActiveSheet()
            ->setCellValue($list[0] . '3', '中文名')
            ->setCellValue($list[1] . '3', '库存sku')
            ->setCellValue($list[2] . '3', '旧库存sku')
            ->setCellValue($list[3] . '3', 'spu')
            ->setCellValue($list[4] . '3', '销售sku数量')
            ->setCellValue($list[5] . '3', '平台')
            ->setCellValue($list[6] . '3', '大类')
            ->setCellValue($list[7] . '3', '二类')
            ->setCellValue($list[8] . '3', '三类')
            ->setCellValue($list[9] . '3', '运营人员');


        // 填充第n(n>=2, n∈N*)行数据
        $length = count($data);
        for ($i = 0; $i < $length; $i++) {
            $obj->getActiveSheet()->setCellValue($list[0] . ($i + 4), $data[$i]['name'], \PHPExcel_Cell_DataType::TYPE_STRING);//将其设置为文本格式
            $obj->getActiveSheet()->setCellValue($list[1] . ($i + 4), $data[$i]['custom_sku'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[2] . ($i + 4), $data[$i]['old_custom_sku'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[3] . ($i + 4), $data[$i]['spu'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[4] . ($i + 4), $data[$i]['sku_count'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[5] . ($i + 4), $data[$i]['platform'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[6] . ($i + 4), $data[$i]['one_cate'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[7] . ($i + 4), $data[$i]['two_cate'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[8] . ($i + 4), $data[$i]['three_cate'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[9] . ($i + 4), $data[$i]['operate_user'], \PHPExcel_Cell_DataType::TYPE_STRING);
        }

        // 设置加粗和左对齐
        foreach ($list as $col) {
            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($col . '1')->getFont()->setBold(true);
            // 设置第1-n行，左对齐
            for ($i = 1; $i <= $length + 1; $i++) {
                $obj->getActiveSheet()->getStyle($col . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            }
        }

        // 设置列宽
        $obj->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('B')->setWidth(30);
        $obj->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('J')->setWidth(20);

        // 导出
        ob_clean();
        if ($fileType == 'xls') {
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xls');
            header('Cache-Control: max-age=1');
            $objWriter = new \PHPExcel_Writer_Excel5($obj);
            $objWriter->save('php://output');
            exit;
        } elseif ($fileType == 'xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');
            header('Cache-Control: max-age=1');
            $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
            $objWriter->save('php://output');
            exit;
        }
    }
    //excel导出 -渠道sku
    public function ExcelSku($params){
        $data = json_decode(json_encode($params), true);
        $obj = new \PHPExcel();


        $fileName = "销售sku列表" . date('Y-m-d');
        $fileType = 'xlsx';

        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('销售sku列表'); //设置标题

        // 设置当前sheet
        $obj->setActiveSheetIndex(0);

        // 设置当前sheet的名称
        $obj->getActiveSheet()->setTitle('销售sku列表');

        // 列标
        $list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I','J','k'];

        // 填充第一行数据
        $obj->getActiveSheet()
            ->setCellValue($list[0] . '3', '中文名')
            ->setCellValue($list[1] . '3', '库存sku')
            ->setCellValue($list[2] . '3', '销售sku')
            ->setCellValue($list[3] . '3', '旧销售sku')
            ->setCellValue($list[4] . '3', 'spu')
            ->setCellValue($list[5] . '3', '平台')
            ->setCellValue($list[6] . '3', '店铺')
            ->setCellValue($list[7] . '3', '大类')
            ->setCellValue($list[8] . '3', '二类')
            ->setCellValue($list[9] . '3', '三类')
            ->setCellValue($list[10] . '3', '运营人员');


        // 填充第n(n>=2, n∈N*)行数据
        $length = count($data);
        for ($i = 0; $i < $length; $i++) {
            $obj->getActiveSheet()->setCellValue($list[0] . ($i + 4), $data[$i]['name'], \PHPExcel_Cell_DataType::TYPE_STRING);//将其设置为文本格式
            $obj->getActiveSheet()->setCellValue($list[1] . ($i + 4), $data[$i]['custom_sku'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[2] . ($i + 4), $data[$i]['sku'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[3] . ($i + 4), $data[$i]['old_sku'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[4] . ($i + 4), $data[$i]['spu'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[5] . ($i + 4), $data[$i]['platform'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[6] . ($i + 4), $data[$i]['shop_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[7] . ($i + 4), $data[$i]['one_cate'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[8] . ($i + 4), $data[$i]['two_cate'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[9] . ($i + 4), $data[$i]['three_cate'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[10] . ($i + 4), $data[$i]['operate_user'], \PHPExcel_Cell_DataType::TYPE_STRING);
        }

        // 设置加粗和左对齐
        foreach ($list as $col) {
            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($col . '1')->getFont()->setBold(true);
            // 设置第1-n行，左对齐
            for ($i = 1; $i <= $length + 1; $i++) {
                $obj->getActiveSheet()->getStyle($col . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            }
        }

        // 设置列宽
        $obj->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('B')->setWidth(30);
        $obj->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('J')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('K')->setWidth(20);

        // 导出
        ob_clean();
        if ($fileType == 'xls') {
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xls');
            header('Cache-Control: max-age=1');
            $objWriter = new \PHPExcel_Writer_Excel5($obj);
            $objWriter->save('php://output');
            exit;
        } elseif ($fileType == 'xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');
            header('Cache-Control: max-age=1');
            $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
            $objWriter->save('php://output');
            exit;
        }
    }

    public function DelCache($params){

        $type = $params['type']??'all';
        switch ($type) {
            case 'img':
                # code...
                Redis::Del('datacache:spu_imgs');
                Redis::Del('datacache:base_spu_img');
                Redis::Del('datacache:customsku_img');
                break;
            case 'all':
                # code...
                Redis::Del('datacache:base_spu_id');
                Redis::Del('datacache:base_spu_img');
                Redis::Del('datacache:custom_sku_id');
                Redis::Del('datacache:customsku_img');
                $news = Redis::Keys('datacache:new*');
                if($news){
                    Redis::Del($news);
                }
                $olds = Redis::Keys('datacache:old*');
                if($olds){
                    Redis::Del($olds);
                }
                $selfs = Redis::Keys('datacache:self*');
                if($selfs){
                    Redis::Del($selfs);
                }

                Redis::Del('datacache:shop');
                Redis::Del('datacache:sku_id');
                Redis::Del('datacache:spu_id');
                Redis::Del('datacache:spu_imgs');
                Redis::Del('fasin_res');
                Redis::Del('datacache:users');
                Redis::Del('datacache:spushop');
                break;
            default:
                # code...
                Redis::Del('datacache:base_spu_id');
                Redis::Del('datacache:base_spu_img');
                Redis::Del('datacache:custom_sku_id');
                Redis::Del('datacache:customsku_img');
                $news = Redis::Keys('datacache:new*');
                if($news){
                    Redis::Del($news);
                }
                $olds = Redis::Keys('datacache:old*');
                if($olds){
                    Redis::Del($olds);
                }
                $selfs = Redis::Keys('datacache:self*');
                if($selfs){
                    Redis::Del($selfs);
                }

                Redis::Del('datacache:shop');
                Redis::Del('datacache:sku_id');
                Redis::Del('datacache:spu_id');
                Redis::Del('datacache:spu_imgs');
                Redis::Del('datacache:users');
                Redis::Del('datacache:spushop');
                Redis::Del('fasin_res');
                break;
        }
        return ['type'=>'success','msg'=>'清除成功'];
    }

    //删除日志 type 1 spu 2custom_sku 3sku
    public function DelLog($params){
        $id = $params['id'];
        $log['type'] = $params['type'];

        if($log['type']==1){
            //spu
            $res = Db::table('self_spu')->where('id',$id)->first();
            if($res){
                $log['name'] = $res->spu;
                Redis::Hdel('datacache:self_spu',$id);
            }else{
                return false;
            }
           
        }elseif($log['type']==2){
            //库存sku
            $res = Db::table('self_custom_sku')->where('id',$id)->first();
            if($res){
                Db::table('self_group_custom_sku')->where('custom_sku',$res->custom_sku)->delete();
                $log['name'] = $res->custom_sku;
                Redis::Hdel('datacache:self_custom_sku',$log['name']);
            }else{
                return false;
            }
            

        }elseif($log['type']==3){
            //sku
            $res = Db::table('self_sku')->where('id',$id)->first();
            if($res){
                $log['name'] = $res->sku;
                Redis::Hdel('datacache:self_sku',$log['name']);
            }else{
                return false;
            }

        }
        $log['user_id'] = $params['user_id'];
        $log['create_time'] = time();

        $res = Db::table('self_del_log')->insert($log);
        if(!$res){
            return false;
        }
        return true;

    }

    private function _checkSelfSpuColorEditParams($params)
    {
        if (isset($params['id'])){
            $spuColorMdl = $this->selfSpuColorModel::query()
                ->where('id', $params['id'])
                ->first();
            if (empty($spuColorMdl)){
                throw new \Exception('未查询到该spu数据！');
            }
        }else{
            throw new \Exception('未给定标识！');
        }

        if (isset($params['order_start_quantity']) && $params['order_start_quantity'] < 0){
            throw new \Exception('起订量数量不正确！');
        }

        return true;
    }


    //添加产品分类
    public function AddProductCate($params){

        $name = $params['name'];
        $token = $params['token'];
        $create_user = db::table('users')->where('token',$token)->first()->Id;
        $i['name'] = $name;
        if(isset($params['cate_id'])){
            $i['cate_ids'] = implode(',',$params['cate_id']);
        }

        if(isset($params['user_id'])){
            $i['user_ids'] = implode(',',$params['user_id']);
        }


        if(isset($params['type'])){
            $i['type'] = $params['type'];
        }

        
        if(isset($params['platform_id'])){
            $i['platform_id'] = $params['platform_id'];
        }


        $i['create_user'] = $create_user;


        if(isset($params['product_cate_id'])){
            db::table('product_cate')->where('id',$params['product_cate_id'])->update($i);
            return ['type'=>'success','msg'=>'修改成功'];
        }


        db::table('product_cate')->insert($i);
        return ['type'=>'success','msg'=>'添加成功'];
        

       
    }


    
    //修改产品分类
    public function UpdateProductCateInfo($params){
        $id = $params['id'];
        $value = $params['value'];
        db::table('product_cate_info')->where('id',$id)->update(['value'=>$value]);
        return ['type'=>'success','msg'=>'修改成功'];   
    }

    //删除产品分类
    public function DelProductCate($params){
        db::table('product_cate')->where('id',$params['id'])->delete();
        return ['type'=>'success','msg'=>'删除成功'];
    }

    //查看产品分类
    public function GetProductCate($params){

                
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
    
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }


        $product = db::table('product_cate');
        if(isset($params['product_cate_id'])){
            $product =$product->where('id',$params['product_cate_id']);
        }
        $type = $params['type']??1;
        $product =$product->where('type',$type);
        if(isset($params['platform_id'])){
            $product =$product->where('platform_id',$params['platform_id']);
        }

        $totalNum  = $product->count();
        $products = $product->offset($page)->limit($limit)->get();
        $datas = [];
        if($products){

            foreach ($products as $product) {
                # code...
                $data = [];
                $cates = [];
                $users = [];
                $data['create_user'] = $this->GetUsers($product->create_user)['account'];
                $data['create_user_id'] = $product->create_user;
                $data['product_cate_id'] = $product->id;
                $data['name'] = $product->name;
                $data['platform_id'] = $product->platform_id;
                $data['platform'] = $this->GetPlatform($product->platform_id)['name']??'';
                $user = explode(',',$product->user_ids);
                $cate = explode(',',$product->cate_ids);

                foreach ($user as $user_id) {
                    # code...\
                    $users['user_name']= $this->GetUsers($user_id)['account'];
                    $users['user_id']= $user_id;
                    $data['user'][] = $users;
                }
    

                foreach ($cate as $cate_id) {
                    # code...
                    if($cate_id>0){
                        $three_cate = db::table('self_category')->where('id',$cate_id)->first();
                        // if(!$three_cate){
                        //     return['type'=>'fail','msg'=>'该类目不存在'.$cate_id];
                        // }
                        $two_cate = db::table('self_category')->where('id',$three_cate->fid)->first();
        
                        $one_cate =  db::table('self_category')->where('id',$two_cate->fid)->first();
                        $cate_name = $one_cate->name.'-'.$two_cate->name.'-'.$three_cate->name;
                        $cates['cate_name'] = $cate_name;
                        $cates['one_cate_id'] = (int)$one_cate->Id;
                        $cates['two_cate_id'] = (int)$two_cate->Id;
                        $cates['three_cate_id'] = (int)$cate_id;
                        $data['cate'][] = $cates;
                    }

                }
                $datas[] = $data;
            }
     
        }

        return ['type'=>'success','data'=>['data'=>$datas,'totalNum'=>$totalNum]];

    }


    //设置面料
    public function AddProductCateInfo($params){
        $i['product_cate_id'] = $params['product_cate_id'];
        $i['type'] = $params['type'];
        $i['value'] = $params['value'];
        $i['create_user'] = $params['user_id'];
        $i['create_time'] =date('Y-m-d H:i:s',time());
        db::table('product_cate_info')->insert($i);
        return ['type'=>'success','msg'=>'添加成功'];
    }


    //查询面料
    public function GetProductCateInfo($params){
        $type = $params['type'];
        $id = $params['id'];
        $list = db::table('product_cate_info')->where('product_cate_id',$id )->where('type',$type)->get();
        if(!$list){
            $list = [];
        }else{
            foreach ($list as $v) {
                # code...
                $v->create_user_id = $v->create_user;
                $v->create_user = $this->GetUsers($v->create_user)['account'];
                
            }
        }
    
        return ['type'=>'success','data'=>$list];
    }

    //删除面料
    public function DelProductCateInfo($params){
        $id = $params['id'];
        db::table('product_cate_info')->where('id',$id)->delete();
        return ['type'=>'success','msg'=>'删除成功'];
    }

    //根据base_spu_id查询面料选项
    public function GetProductCateInfoByBaseSpuId($params){
        $type = $params['type'];
        $data = [];
        $base_spu = db::table('self_base_spu')->where('id',$params['base_spu_id'])->first();
        if($base_spu){
            $product_cate = db::table('product_cate')->whereRaw("find_in_set({$base_spu->three_cate_id},cate_ids)")->first();
            if($product_cate){
                $data =  db::table('product_cate_info')->where('product_cate_id',$product_cate->id )->where('type',$type)->get();
            }
        }
        return ['type'=>'success','data'=>$data];
    }

    //根据user_id,base_spu_id查询是否有权限
    public function GetProductCateAuthByBaseSpuId($params){
        $user_id = $params['user_id'];
        $is_auth = 0;
        $base_spu = db::table('self_base_spu')->where('id',$params['base_spu_id'])->first();
        if($base_spu){
            $product_cate = db::table('product_cate')->whereRaw("find_in_set({$base_spu->three_cate_id},cate_ids)")->whereRaw("find_in_set({$user_id},user_ids)")->first();
            if($product_cate){
                $is_auth = 1;
            }
        }
        return ['type'=>'success','data'=>['is_auth'=>$is_auth]];
    }


}